NODE.JS Introduction

Node.js = Runtime Environment + JavaScript Library

first application

install link
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Hello World!');
node myfirst.js

var job=require("./Job");

NPM (Node Package Manager)
Online repositories for node.js packages/modules which are searchable

//update npm 
$ sudo npm install npm -g

//to install npm module
$ npm install <Module Name>
$ npm install express

//to install module in globa
$ npm install express -g

//to install package.json modules
npm instsll 

//to install module and add it to debendencies in package.json
npm install linq -P

//to install module and add it to devDependencies in package.json
npm install nodemon -D

//check all modules installed globally
$ npm ls -g

//uninstall module 
$ npm uninstall express

//update module 
$ npm update express

$ npm search express
var express = require('express');

package.json scripts

"scripts": {
    "start": "node --inspect=5858 -r ts-node/register ./src/server.ts",
    "start:watch": "nodemon",
    "build": "tsc  && copyfiles -u 1 ./src/**/*.env ./dist",
    "prod": "npm run build && npm run start",
    "dev": "nodemon ./src/server.ts",
    "debug": "nodemon --inspect ./src/server.ts",
    "baslat": "npm run build  && forever start ./dist/server.js"
npm run start or npm start 
npm run prod or npm prod
npm debug or npm run debug

Process Module

The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require()

process.stderr.write("hello world");
process.stdin.on("data", (data) => {
    const name = data.toString().trim().toUpperCase();
    if (name !== "") {
        process.stdout.write(`Hello ${name}!`);
    } else {
        process.stderr.write("Input was empty.");
process.on('exit', function () {
  fs.writeFileSync('/tmp/myfile', 'This MUST be saved on exit.');
process.on('uncaughtException', function (err) {
  console.error('An uncaught error occurred!');

The default behavior on uncaughtException is to print a stack trace and exit – using the above, your program will display the message provided and the stack trace, but will not exit.

There are also a variety of methods attached to the process object, many of which deal with quite advanced aspects of a program. We’ll take a look at a few of the more commonly useful ones, while leaving the more advanced parts for another article.

process.exit exits the process. If you call an asynchronous function and then call process.exit() immediately afterwards, you will be in a race condition – the asynchronous call may or may not complete before the process is exited. process.exit accepts one optional argument – an integer exit code. 0, by convention, is an exit with no errors.

process.cwd returns the ‘current working directory’ of the process – this is often the directory from which the command to start the process was issued.

process.chdir is used to change the current working directory. For example:

setTimeout(function () {
  // code here
}, 0)

process.nextTick(function () {//prefer this
  console.log('Next trip around the event loop, wheeee!')

The process.argv property returns an array containing the command-line arguments passed when the Node.js process was launched.

The child_proccess Module

shell.exec("ping",(error, stdout, stderr)=>{
    if (error) {
        console.log(`error: ${error.message}`);
    if (stderr) {
        console.log(`stderr: ${stderr}`);
    console.log(`stdout: ${stdout}`);
const { spawn } = require("child_process");

const ls = spawn("ls", ["-la"]);

ls.stdout.on("data", data => {
    console.log(`stdout: ${data}`);

ls.stderr.on("data", data => {
    console.log(`stderr: ${data}`);

ls.on('error', (error) => {
    console.log(`error: ${error.message}`);

ls.on("close", code => {
    console.log(`child process exited with code ${code}`);

fs and path Modules


// Returns: 'quux.html'

path.basename('/foo/bar/baz/asdf/quux.html', '.html');
// Returns: 'quux'

// Returns: '/foo/bar/baz/asdf'

// Returns: '.html'

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'

fs sync

const fs = require("fs");
const path = require("path");
const filepath = path.join(process.cwd(), "hello.txt");
const contents = fs.readFileSync(filepath, "utf8");
console.log("File Contents:", contents);
const upperContents = contents.toUpperCase();
fs.writeFileSync(filepath, upperContents);
console.log("File updated.");

fs async

const fs = require("fs");
const path = require("path");
const filepath = path.join(process.cwd(), "hello.txt");
fs.readFile(filepath, "utf8", (err, contents) => {
  if (err) {
    return console.log(err);
  console.log("File Contents:", contents);
  const upperContents = contents.toUpperCase();
  updateFile(filepath, upperContents);
function updateFile(filepath, contents) {
  fs.writeFile(filepath, contents, (err) => {
    if (err) throw err;
    console.log("File updated.");

fs promises

const fs = require("fs").promises;
const path = require("path");
const filepath = path.join(process.cwd(), "hello.txt");
async function run() {
  try {
    const contents = await fs.readFile(filepath, "utf8");
    console.log("File Contents:", contents);
  } catch (error) {
function printMetadata(file) {
  try {
    const fileStats = fs.statSync(file);
  } catch (err) {
    console.error("Error reading file path:", file);

Watching for file updates
Node.js’s fs module provides functionality that enables you to watch files and track when files or directories are created, updated, or deleted.
In this recipe, we’ll create a small program named watch.js that watches for changes in a file using the watchFile() API and then prints a message when a change has occurred.

const fs = require("fs");
const file = "./file.txt";
const moment = require("moment");, (eventType, filename) => {
    const time = moment().format("MMMM Do YYYY, h:mm:ss a");
    return console.log(`${filename} updated ${time}`);


var events = require('events');

let emitter=new events.EventEmitter();
emitter.on("click",()=>{console.log("call 1")});
emitter.on("click",()=>{console.log("call 2")});
emitter.on("click",()=>{console.log("call 3")});
emitter.emit("click");//call 1 call 2 call 3
var events = require('events');

function fun1(){
function fun2(){

let emitter=new events.EventEmitter();


Pure JavaScript is Unicode friendly, but it is not so for binary data. While dealing with TCP streams or the file system, it’s necessary to handle octet streams. Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.Buffer class is a global class that can be accessed in an application without importing the buffer module.

var buf = new Buffer(10);
var buf = new Buffer([10, 20, 30, 40, 50]);
var buf = new Buffer("Simply Easy Learning", "utf-8");
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");

console.log("Octets written : "+  len);//20
buf.toString([encoding][, start][, end]) 
Live Demo
buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
  buf[i] = i + 97;

console.log( buf.toString('ascii'));       // outputs: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5));   // outputs: abcde
console.log( buf.toString('utf8',0,5));    // outputs: abcde
console.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde
var buffer1 = new Buffer('TutorialsPoint ');
var buffer2 = new Buffer('Simply Easy Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);

console.log("buffer3 content: " + buffer3.toString());
var buffer1 = new Buffer('ABC');

//copy a buffer
var buffer2 = new Buffer(3);
console.log("buffer2 content: " + buffer2.toString());
Live Demo
var buffer1 = new Buffer('TutorialsPoint');

//slicing a buffer
var buffer2 = buffer1.slice(0,9);
console.log("buffer2 content: " + buffer2.toString());


var fs = require("fs");
var data = '';

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Set the encoding to be utf8. 

// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
   data += chunk;

readerStream.on('end',function() {

readerStream.on('error', function(err) {

console.log("Program Ended");//call first
var fs = require("fs");
var data = 'Simply Easy Learning';

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Write the data to stream with encoding to be utf8

// Mark the end of file

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
   console.log("Write completed.");

writerStream.on('error', function(err) {

console.log("Program Ended");
var fs = require("fs");

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Pipe the read and write operations
// read input.txt and write data to output.txt

console.log("Program Ended");