Node.js For Beginner
Introduction
Node.js is a server-side platform built on Google Chrome’s JavaScript Engine (V8 Engine). Node is a runtime environment for executing JavaScript code. Node is non blocking, node has a single thread that allocated to handle multiple request. Node continuously monitoring Event Queue on background
Features of Node.js
Following are some of the features:
- Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call.
- Very Fast − Being built on Google Chrome’s V8 JavaScript Engine, Node.js library is very fast in code execution.
- Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server.
- No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks.
- Node is ideal for I/O intensive apps, do not use Node for CPU intensive apps like video encoding / image manipulation
Let’s start coding
Prequisites
- Node.js
- Visual Studio Code
Hello World Application
- Open your command prompt, then check if node.js is installed successfully or not by checking node.js version using below command
node -v
It will display node.js version
- Then on command prompt, navigate to your project directory, create new folder called “node” by using below command
mkdir node
- Navigate to directory “node” then open visual studio code by below command
code .
- Create new file on Visual Studio Code called “helloWorld.js”, by right clicking mouse then choose new File
- Then let’s write a javascript function for displaying hello world on console, you could do that by using below code
function helloWorld(){console.log("Hello World");}helloWorld();
- Then on command prompt, run the HelloWorld.js by using below command
node [Javascript File]
In my case :
node HelloWorld.js
Check Module Properties
In node, every file is a module, the variable and functions defined in that file are scoped to that module.
We could check module properties by using below steps
- Create new file app.js
- Write below code inside app.js
Console.log(module);
- Then open command prompt and execute below command to run app.js
node app.js
- It will display below result
Note : you could see that exports properties are empty, if we want to expose a module (make it public) you need to export it. Please follow “Load Module” section
Load Module
Below are steps how to load module on node.js
- Create new file called “logger.js” for logging message, we will use this logger module in other module
- Then put below code in logger.js
function log(message){ console.log(message);}module.exports.log = log;
- module.exports is a syntax to export properties / function. So module.exports.log = log will export log function, so now we could call log function from other module. We could use exports.log = log too.
- on app.js, we will load logger.js module, we could do that by syntax “require”, this syntax has 1 parameter which is the name / path or the target module. So we will use below code to load logger module which is in same folder
require('./logger')
If your module is in subfolder, you could load in by below code
require('./subFolder/logger')
If your module is in parent folder, you could load in by below code
require('../logger')
- So to use log function on app.js, we could use below code
const logger = require('./logger')logger.log('Test Log');
- Then run again app.js on cmd, it will display the message on cmd
Note : we use const instead of var because we don’t want we overwrite our module object
How to trace node error
We could trace node error message by using several tools, 1 of the tool is jshint, below how to install jshint
- Open CMD, then execute below command
npm install -g jshint
- Then execute below command
jshint [JS Filename]
e.g :
jshint app.js
Node.js Built-in Modules
You could find built-in node.js module on https://nodejs.org/dist/latest-v12.x/docs/api/
For example, let’s try Path Module
- Open your app.js file, then put below code inside app.js, this code will parse our app.js filepath string to path object, then you could get filename or file extension later from path object
const path = require('path');var fileObj = path.parse(__filename);console.log(fileObj);
- Then open CMD, then run app.js
node app.js
another example, let’s use OS module
const os = require('os');var totalMemory = os.totalmem();console.log(`Total Memory : ${totalMemory}`)
And on above code, you could see we use string template from ES6, for use this you only need to change single quote to `
Then you could use the variable by using ${variableName}
Events
Event is a signal that indicates that something has happened in our application, e.g : in node we have HTTP module, we could use that to build a web server, so application will listen top a given port and every time we receive a request on that port. HTTP class will raise a new event to read the request and return response.
We will begin with building event listener and event emitter
- Open your app.js file and put below code
const EventEmitter = require('events');const emitter = new EventEmitter();emitter.on('messageLogged', (arg) =>{console.log("Listener called", arg);})emitter.emit('messageLogged', { id: 1, message:'hello world'});
EventEmitter is a class, so to use it, we need to instantiate it by “new” syntax
Then we create a listener using “emitter.on” syntax, first parameter is for message name that we listen, and second parameter is a function
After that we create an event emitter by using emitter.emit(‘[MessageName’, argument);
- Run the application by executing
node app.js
HTTP Server
We could build a http server by using http module by using below code on app.js
const http = require('http');const server = http.createServer((req, res) => {if(req.url === '/'){res.write('Hello World');res.end();}});server.listen(4000);console.log('Listening on port 4000');
So node will listen to port 4000, and if there is request from port 4000, it will return response “Hello World”
Now run your app.js by below command
node app.js
Open your browser and navigate to localhost:4000, it will display “Hello World”
Thanks for reading