This content goes along with the video Introduction to Node.js.
Resources:
- Node.js Web Site
- How do I read files in node.js?
- Node "fs" API documentation
- Lorem Ipsum
- The Node.js Way - Understanding Error-First Callbacks
- Writing files in Node.js
- BUILD YOUR FIRST HTTP SERVER IN NODE.JS
- Hypertext Transfer Protocol (Wikipedia)
- Content types (MIME types) W3C Spec
- UTF-8 (Wikipedia)
- JSBin HTML Boilerplate
- Streamgraph with Padding
- Express NPM Package
- Specifics of package.json handling
- Serving static files in Express
- Datavis.tech
When you have your server running, go to http://localhost:3000/
Code:
index.html main.js mainFileServer.js
greet.js
function greet(name){
return "Hello " + name;
}
module.exports = greet;
main.js (using greet.js)
var greet = require("./greet");
console.log(greet("World"));
test.txt
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
main.js (reading a file)
var fs = require("fs");
fs.readFile("test.txt", "utf8", function (error, text){
console.log(text);
});
main.js (writing a file)
var fs = require("fs");
fs.writeFile("testWrite.txt", "Hello World", function (error){
console.log("wrote file");
});
testWrite.txt
Hello World
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test page</title>
</head>
<body>
<h1>Hello Node.js!</h1>
</body>
</html>
main.js (serving index.html)
var http = require('http');
var fs = require('fs');
var server = http.createServer(function (request, response){
response.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('index.html', 'utf8', function (err, text){
response.end(text);
});
});
server.listen(3000, function(){
console.log('Server listening at http://localhost:3000');
});
package.json
{
"name": "testing",
"version": "1.0.0",
"description": "Testing stuff.",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Curran Kelleher",
"license": "ISC",
"dependencies": {
"express": "^4.13.4"
}
}
Commands used throughout the video:
mkdir testing
cd testing/
clear
ls
vim main.js
ls
cat main.js
node main.js
vim main.js
ls
clear
vim main.js
clear
npm install express
npm init
npm install -S express
ls
ls node_modules/
cat package.json