Inbuilt Modules In Node js

Inbuilt Modules In Node js

Introduction

`1. There are 4 inbuilt Modules in Nod

  • OS

  • Path

  • File System

  • HTTP

os

  1. The os module provides API for getting information about hardware related like CPU, memory, directories, IP address and many more.

    In this tutorial, we will learn basics methods and some more concepts of os module.

    To start working with the os module, we have to import osmodule in our project.

     const os = require('os');
    
  2. os.arch()

    This method will return the architecture of the processor.

     const os = require('os');
     console.log(os.arch());
    
  3. os.cpus()

    This method returns an array of the object which contains information of logical CPUs.

     const os = require('os');
     console.log(os.cpus());
    
  4. os.freemem()

    This method returns free main memory bytes in integer.

     const os = require('os');
     console.log(os.freemem());
    
  5. os.getPriority(pid)

     const os = require('os');
     console.log(os.getPriority(13512));
    
  6. os.homedir()

    This method current user’s home directory as a string.

     const os = require('os');
     console.log(os.homedir());
    
  7. os.hostname()

    This method returns the hostname of the operating system i.e. the computer name as a string.

     const os = require('os');
     console.log(os.hostname());
    
  8. os.networkInterfaces()

    This method returns objects containing information about network interfacing devices.

     const os = require('os');
     console.log(os.networkInterfaces());
    
  9. os.platform()

    This method return information about platform i.e. operation system platform like win64 arm linux etc.

     const os = require('os');
     console.log(os.platform());
    
  10. os.totalmem()

    This method returns total system memory in bytes as a string.

    const os = require('os');
    console.log(os.totalmem());
    
  11. os.userInfo([options])

    This method returns the current user. The returned object includes the username, uid, gid, shell, and homedir. On Windows, the uid and gid fields are -1, and shell is null.

    options: If encoding is set to 'buffer', the username, shell, and homedir values will be Buffer instances. Default: 'utf8' .

const os = require('os');
console.log(os.userInfo());

PATH

  1.  var path = require('path');
     var filename = path.basename('/Users/Refsnes/demo_path.js');
     console.log(filename);
    
  2. | Method | Description | | --- | --- | | basename() | Returns the last part of a path | | delimiter | Returns the delimiter specified for the platform | | dirname() | Returns the directories of a path | | extname() | Returns the file extension of a path | | format() | Formats a path object into a path string | | isAbsolute() | Returns true if a path is an absolute path, otherwise false | | join() | Joins the specified paths into one | | normalize() | Normalizes the specified path | | parse() | Formats a path string into a path object | | posix | Returns an object |

File Module

  • Synchronous File operations

  • Asynchronous File operations

  1. Synchronous File Operations

    • Synchronous programming means that the code runs in the sequence it is defined. In a synchronous program, when a function is called and has returned some value, only then will the next line be executed.
  2. Asynchronous Operations

    • In computer programming, asynchronous operation means that a process operates independently of other processes, whereas synchronous operation means that the process runs only as a result of some other process being completed or handed off.

    • Can be achieved in two ways

      • Using Promise

      • Using sync await

example

```javascript
// 1. Using async await
import fs from 'fs';

async function myF() {
  let names;
  try {
    names = await fs.readdir('path/to/dir');
  } catch (e) {
    console.log('e', e);
  }
  if (names === undefined) {
    console.log('undefined');
  } else {
    console.log('First Name', names[0]);
  }
}

myF()
```
//example 2 using promise
doSomething(function (result) {
  doSomethingElse(result, function (newResult) {
    doThirdThing(newResult, function (finalResult) {
      console.log(`Got the final result: ${finalResult}`);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

HTTP

  1. Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).

    To include the HTTP module, use the require() method:

     var http = require('http');
    
     var http = require('http');
    
     //create a server object:
     http.createServer(function (req, res) {
       res.write('Hello World!'); //write a response to the client
       res.end(); //end the response
     }).listen(8080); //the server object listens on port 8080
    
  1. The function passed into the http.createServer() method, will be executed when someone tries to access the computer on port 8080.

  2. Adding an HTTP heade

    • If the response from the HTTP server is supposed to be displayed as HTML, you should include an HTTP header with the correct content type:
```javascript
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('Hello World!');
  res.end();
}).listen(8080);
```
  1. Read the Query String

    The function passed into the http.createServer() has a req argument that represents the request from the client, as an object (http.IncomingMessage object).

    This object has a property called "url" which holds the part of the url that comes after the domain name:

     var http = require('http');
     http.createServer(function (req, res) {
       res.writeHead(200, {'Content-Type': 'text/html'});
       res.write(req.url);
       res.end();
     }).listen(8080);
    
  2. Split the Query String

     var http = require('http');
     var url = require('url');
    
     http.createServer(function (req, res) {
       res.writeHead(200, {'Content-Type': 'text/html'});
       var q = url.parse(req.url, true).query;
       var txt = q.year + " " + q.month;
       res.end(txt);
     }).listen(8080);