Node.js basics

If you have some basic knowledge about Node.js, you can skip this chapter or just regard it as a reference.

Node.js version “Hello World”

  1. console.log('Hello World');
  • Run the script on your terminal
  1. node test.js

Version management of Node.js

With the effort of worlds’s contributors, Node.js is getting better and better. So it is a usual for us to change and update the version of Node.js on our machine.

I recommend NVM to do this stuff. Its features are complete and convinent. For more infomation, you could visit its Github page.

Module system

Node.js implement the CommonJS sepc):

  • Use global to define a global variable:
  1. global.test =true;
  • Use require to import a module:
  1. var fs = require('fs');
  • Use module.exports to exports a module:
  1. module.exports =function(){
  2. console.log('Hello Node.js');
  3. };
  • Use exports to export multiple methods or Object:
  1. =function(){};
  2. =function(){};

The simplest Node.js server:

  1. var http = require('http');
  2. http.createServer(function(req, res){
  3. res.send('Hello');
  4. res.end();
  5. }).listen(3000);

Visit it on localhost:300 and you could see the word “Hello”.