NODE.JS Introduction

Node.js = Runtime Environment + JavaScript Library

first application

install link

https://github.com/nodesource/distributions/blob/master/README.md
var http = require('http');

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

Modules

module.exports.name="mohammed";
module.exports.surName="alabdali";
var job=require("./Job");
console.log(job.name,job.surName);

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

//search 
$ 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!');
  console.error(err.stack);
});

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 malabdali.com",(error, stdout, stderr)=>{
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    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

Path

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

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

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

path.extname('index.html');
// 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) {
    console.error(error);
  }
}
run();
function printMetadata(file) {
  try {
    const fileStats = fs.statSync(file);
    console.log(fileStats);
  } 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");
fs.watch(file, (eventType, filename) => {
    const time = moment().format("MMMM Do YYYY, h:mm:ss a");
    return console.log(`${filename} updated ${time}`);
});

Events

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(){
    console.log("fun1");
}
function fun2(){
    console.log("fun2");
}

let emitter=new events.EventEmitter();
emitter.addListener("click",fun1);
emitter.addListener("click",fun2);
emitter.emit("click");//fun1,fun2
emitter.removeListener("click",fun1);
emitter.emit("click");//fun2

buffer

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);
buffer1.copy(buffer2);
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());

Streams

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

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

// Set the encoding to be utf8. 
readerStream.setEncoding('UTF8');

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

readerStream.on('end',function() {
   console.log(data);
});

readerStream.on('error', function(err) {
   console.log(err.stack);
});

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
writerStream.write(data,'UTF8');

// Mark the end of file
writerStream.end();

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

writerStream.on('error', function(err) {
   console.log(err.stack);
});

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
readerStream.pipe(writerStream);

console.log("Program Ended");