Nodejs express

Express Overview

Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications. Following are some of the core features of Express framework −

  • Allows to set up middlewares to respond to HTTP Requests.
  • Defines a routing table which is used to perform different actions based on HTTP Method and URL.
  • Allows to dynamically render HTML Pages based on passing arguments to templates.

Installing Express

Firstly, install the Express framework globally using NPM so that it can be used to create a web application using node terminal.

$ npm install express --save

The above command saves the installation locally in the node_modules directory and creates a directory express inside node_modules. You should install the following important modules along with express −

  • body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
  • cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
  • multer − This is a node.js middleware for handling multipart/form-data.
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save

Routing

var express = require('express');
var app = express();

app.get('/', function (req, res) {
   res.send('Hello World');
})

app.get(/a/, function (req, res) {//any url contains a
  res.send('/a/')
})

app.get('/name/:name',function (req,res){//req.params={name:"mohammed"}
    res.send("hello world");
});

var server = app.listen(8081, function () {
   var host = server.address().address;
   var port = server.address().port;
   
   console.log("Example app listening at http://%s:%s", host, port)
})
app.route('/book')
  .get(function (req, res) {
    res.send('Get a random book')
  })
  .post(function (req, res) {
    res.send('Add a book')
  })
  .put(function (req, res) {
    res.send('Update the book')
  })

static files

Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript, etc.
You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this −

app.use(express.static('public'));

upload file

var bodyParser = require('body-parser');
var multer  = require('multer');
let storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null,config.filesUploadPath);
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname);
    },
});

let uploadFile = multer({
    storage: storage,
    limits: { fileSize: config.fileMaxSize }
}).single(config.fileQueryName);

const UploadFile = [uploadFile,async (req, res) => {
    try {
        let file=req[config.fileQueryName];
        fs.renameSync(file.destination+file.originalname,newName);
    } catch (err) {
    }
}];

cookies management

var express      = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/', function(req, res) {
   console.log("Cookies: ", req.cookies)
})
app.listen(8081)

middleware

app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
  res.send('Hello from B!')
})
var cb0 = function (req, res, next) {
  console.log('CB0')
  next()
}

var cb1 = function (req, res, next) {
  console.log('CB1')
  next()
}

var cb2 = function (req, res) {
  res.send('Hello from C!')
}

app.get('/example/c', [cb0, cb1, cb2])//multiple response
let config=require("./config");
let express=require("express");

let app=express();
app.use(function(req,res,next){
    console.log("middleware");
    next();
});
app.get('/name',function (req,res){
    res.send(req.query);
});
let server=app.listen(config.port,()=>{
    console.log(server);
});
var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', function (req, res) {
  res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
  res.send('About birds')
})

module.exports = router

Content-Type: application/json

app.use(express.json())

Content-Type: application/x-www-form-urlencoded

app.use(express.urlencoded({
  extended: true
}))

and you can acess to it by

req.body.fieldName;

raw data

const express=require("express");
const bodyParser = require('body-parser');

let options = {
    inflate: true,
    limit: '100kb',
    type: 'text/plain'
};
let app=express();
app.use(bodyParser.raw(options));

app.post("/hello",(req,res)=>{
    res.send(req.body);//body is string if type: 'text/*' else buffer
})
app.listen(8081,()=>{});

HTTP headers

app.get('/', (req, res) => {
  console.log(req.headers)
})
app.get('/', (req, res) => {
  req.header('User-Agent')
  req.get('User-Agent');
})

Response Methods And Properties

The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.

MethodDescription
res.download()Prompt a file to be downloaded.
res.end()End the response process.
res.json()Send a JSON response.
res.jsonp()Send a JSON response with JSONP support.
res.redirect()Redirect a request.
res.render()Render a view template.
res.send()Send a response of various types.
res.sendFile()Send a file as an octet stream.
res.sendStatus(), res.status(code)Set the response status code and send its string representation as the response body.
res.apphold express app
res.cookie()
res.clearCookie()
res.cookie(name, value [, options])
res.set('Content-Type', 'text/html')
res.type('.html')
// => 'text/html'

res.type('html')
// => 'text/html'

res.type('json')
// => 'application/json'

res.type('application/json')
// => 'application/json'

res.type('png')
// => image/png:

for more visit this link

https://expressjs.com/en/4x/api.html

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");