Node.js Basics
Published: Aug 11, 2018 Tags: web, backend Category: Engineering
Recently, I used Node.js quite a lot to handle personal projects. It is easy to start, and also easy to get wrong. This blog covers the basics part of Node.js development.
Module
Require
Every module in node is singleton.
Use require to use module, the following is the search sequence of require method:
- First find js file
- Then json file
- Then node file
If the module name is index.js, then it is okay just write directory name in the require parameter.
require() can inject objects for dependency injection.
Module exports
From the modele itself, use exports keyword to make properties and methods available outside of the module file.
1 exports.myDateTime = function () {
2 return Date();
3 };
Http module
http module can be used to write header or content. See following example:
1var http = require('http');
2http.createServer(function (req, res) {
3 res.writeHead(200, {'Content-Type': 'text/html'});
4 res.write('Hello World!');
5res.write(req.url); // read query string
6 res.end();
7}).listen(8080);
File module
File module can be used for file system operation.
1require(fs)
2var http = require('http');
3var fs = require('fs');
4http.createServer(function (req, res) {
5 fs.readFile('demofile1.html', function(err, data) {
6 res.writeHead(200, {'Content-Type': 'text/html'});
7 res.write(data);
8 res.end();
9 });
10}).listen(8080);
Other useful methods in file module.
write file: fs.appendfile(), fs.open(), fs.writefile()
delete file: fs.unlink()
rename: fs.rename()
Url module
Url module can be used to parse various parts of url.

1url.parse('https://www.pluralsight.com/search?q=buna')
2
3Url {
4protocol: 'https:',
5slashes: true,
6auth: null,
7host: 'www.pluralsight.com',
8port: null,
9hostname: 'www.pluralsight.com',
10hash: null,
11search: '?q=buna',
12query: 'q=buna',
13pathname: '/search',
14path: '/search?q=buna',
15href: 'https://www.pluralsight.com/search?q=buna' }
example
1http.createServer(function (req, res) {
2 res.writeHead(200, {'Content-Type': 'text/html'});
3 var q = url.parse(req.url, true).query;
4 var txt = q.year + " " + q.month;
5 res.send(txt);
6}).listen(8080);
Use the url for testing: http://localhost:8080/?year=2017&month=July Output is: 2017 July
Event model
The event model of node.js is asymmetric. The core part is event loop.
For example, here is how Node.js handles a file request:
- Sends the task to the computer's file system.
- Ready to handle the next request.
- When the file system has opened and read the file, the server returns the content to the client.
The event loop looks like this:
- The entity that handles external events and converts them into callback invocations
- A loop that picks events from the event queue and pushes their callbacks to the call back stack
- Node will process the event queue when call stack is empty
There are three methods look quite similar, it will be good to understand the difference:
- setTimeout
- setImmediate
- Process.nextTick (not relevant event loop)
NPM
Npm is node package manager, which is the core part of javascript ecosystem.
Commands
Npm start, npm test: will run when there is start/test script in the package.json
Npm -h: to show the help
Npm help: can open a browser
Npm init: will create the package.json
Npm list: list all installed packages
Npm can install global package, and can also install in local repository
Npm can specify the versions when using npm i
Npm can specify environment, e.g. --save, --prod, --dev
NPM can choose install from 'gist' instead of a version, also can install from folder
npm publish: can publish your package to npm registery
Version
Semantic version: major.minor.patch
- Patch increase when bug fixing
- Minor increase when introduce new feature
- Major increase when breaking changes
In the package.json: ^means major version can be greater, ~means minor version can be greater
npm version patch/minor/major to update the version info in the pcakge.json rather than manually change the version (it will also do the git commit for developers)
Others
Difference from client javascript
Javascript in node.js app, differentiate client and server code.
For example:
- server can call require while client can call windows.
- server code modification needs to restart node to see the changes, while client code just need browser refresh.
- console.log in the server code will output the message to terminal app, the client code will output the message the browser console.
Uglify
gulp can uglify your repository
Error code
If there is error, can use res.status(500).send(err) to return the error code
1bookRouter.route('/Books/:bookId').get(function(req, res)) {
2 Book.findById(req.params.bookId, function(err, book) {
3 if (err) {
4 res.status(500).send(err);
5 } else {
6 res.json(book);
7 }
8 })
9}
Compare with Microsoft technologies

Written by Binwei@Singapore