Create a gist now

Instantly share code, notes, and snippets.

plain vanilla node.js intro tutorial to learn a lot in the shortest time.

The plan is to take a simple nodejs server. and add to it simple file serving capabilities. also to have a custom responce to a certien url. to be able to make a simple api in addition of serving files.

goals:

  • to learn read the documentation
  • to understand the whole concept
  • to use some api for hands on expirience
  • streach goal: learn basic npm usage.
//go to nodejs.org and copy the simple hello world code to a file.
// test it go with the browser to http://127.0.0.1:1337/
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1'); // remove the ip argument from listen. otherwise it will bind only to this ip address. and you wont be able to connect if it runs on a server.
console.log('Server running at http://127.0.0.1:1337/');
// 1. go to nodejs.org api documentation and read how to use url.parse
// 2. use parse url and show a different text for a custom url
var http = require('http');
var url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain; charset=UTF-8'});
var purl=url.parse(req.url,true);
if(purl.pathname=='/test')
res.end('Test'); // there is response.write and response.end
// response.end('text') is response.write('text'), then response.end();
else
res.end('Hello World\n');
}).listen(1337);
console.log('Server running at http://127.0.0.1:1337/');
// read in the api documentation about reading files.
// read some file to the output
//
// there are many options actually.
// files coud be read with a callback. - quite efficient and simple i will use this way.
// files coud be read Sync as a return value from the function - blocking the program, this way the program wont be able serve others while waithing for the file to be read from disk.
// a stream could be created and piped to the response stream - most cpu and memory efficient.
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain; charset=UTF-8'});
var purl=url.parse(req.url,true);
if(purl.pathname=='/test')
res.end('Test');
else
fs.readFile('step2.js', function (err, data) {
if (err) throw err;
// console.log(data);
res.end(data);
});
}).listen(1337);
console.log('Server running at http://127.0.0.1:1337/');
// i have orgenized the code and added mime for each condition seperately
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var purl=url.parse(req.url,true);
if(purl.pathname=='/test')
{
res.writeHead(200, {'Content-Type': 'text/plain; charset=UTF-8'});
res.end('Test');
}
else
{
res.writeHead(200, {'Content-Type': 'text/plain; charset=UTF-8'});
fs.readFile('step3.js', function (err, data){
if (err) throw err;
res.end(data);
});
}
}).listen(1337);
console.log('Server running at http://127.0.0.1:1337/');
// check if a file exists - read the api docs to learn how to check if a file exists
// there is a special variable in each module __dirname it contains the directory name of this file
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var purl=url.parse(req.url,true);
if(purl.pathname=='/test')
{
res.writeHead(200, {'Content-Type': 'text/plain; charset=UTF-8'});
res.end('Test');
}
else
{
fs.exists(__dirname+purl.pathname, function (exists) {
if (exists){
res.writeHead(200, {'Content-Type': 'text/plain; charset=UTF-8'});
fs.readFile(__dirname+purl.pathname, function (err, data){
if (err) throw err;
res.end(data);
});
}
else
{
res.writeHead(404, {'Content-Type': 'text/plain; charset=UTF-8'});
res.end('File Not Found');
}
});
}
}).listen(1337);
console.log('Server running at http://127.0.0.1:1337/');
// add mimes
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function(req, res) {
var purl = url.parse(req.url, true);
if (purl.pathname == '/hello') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('hello ' + (purl.query.name||"world") ); // notice i use querystring arguments here http://127.0.0.1:1337/hello?name=me!
} else {
fs.exists(__dirname + purl.pathname, function(exists) {
if (exists) {
var extention = purl.pathname.match(/\..+$/)[0];
var mime = {
'.js': 'text/javascript; charset=UTF-8',
'.txt': 'text/plain; charset=UTF-8',
'.html': 'text/html; charset=UTF-8',
'.png': 'image/png',
'.gif': 'image/gif',
'.jpg': 'image/jpeg'
}
res.writeHead(200, {'Content-Type': mime[extention]});
fs.readFile(__dirname + purl.pathname, function(err, data) {
if (err) throw err;
res.end(data);
});
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('File Not Found');
}
});
}
}).listen(1337);
console.log('Server running at http://127.0.0.1:1337/');

search in google: node.js modules

https://github.com/joyent/node/wiki/modules

to see the whole range of possibilities.

using npm:

as you installed node.js npm is also installed. this is how to use it:

when you start a new project make an empty folder and put there your file. it maybe named index.js, it is also the default file name for a module.

in the command prompt enter this new project folder and run:

npm init

if you are laizy then just press many times Enter and thats it, or you can enter your information there. it will create package.json for you and node_modules folder.

then you can use npm in your program like(run it in your project folder):

npm install --save somepackage 

then you can use this package in your program like:

var somepackage=require('somepackage')

npm documentation:

people usually don't use vanilla node.js

  • people use "async" module or some promises module. to write a less callback based code. and use simple parallel or serial logic or use async foreach or foreach limit for asynchronious batch processing.
  • people use "express" module it is a better equipd http request and http response and http server. it has ./node_modules/express/bin/express --help command that can generate a basic boilerplate.
    • the basic structure of the https server callback is function(req,res,next){}
    • if you like that you see you process it otherwise you modify what you want and call next to ket the handler to process the request.
    • express has basic file server with mimes and everything.
  • people use "mysql" module for database
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment