DEV Community

Cover image for Node.js
Kaushal
Kaushal

Posted on

Node.js

Core things in Node.js

proceses object

  • In the process object, there is an argv property. Which gives us arguments, those we have passed via console.
    console.log(process.argv);
    

process object

  • We can pass any number of arguments as we want, and access it into the script.
    var index = process.argv.indexOf("Hello");
    console.log(process.argv[index]);
    

process object

  • We can also pass arguments as a flag.
    var index = process.argv.indexOf("--words") + 1;
    console.log(process.argv[index]);
    

Alt Text

  • Write on the console using process object.
    process.stdout.write("Hello");
    process.stdout.write("World\n\n");
    

Alt Text

  • Take input from console using process object.

    • But in this case program execution will never stop.
    • We have to stop it manually.
      process.stdin.on("data", (data) => {
      process.stdout.write(data);
      });
      

    Alt Text

    • In below example stop manually process.
      process.stdin.on("data", (data) => {
      process.stdout.write(data);
      process.exit(); // this function call stop the process
      });
      
      Alt Text
  • Handle console logging inside the script.

    • In this example console will clear before each and every print statement.
      var index = 1;
      const interval = setInterval(() => {
      process.stdout.clearLine();
      process.stdout.cursorTo(0);
      process.stdout.write(${index++});
      }, 500);
      setTimeout(() => {
      clearInterval(interval);
      }, 3000);
      
      Alt Text

util module

  • Util module use for logging data on the console like console.log().
    • It displays data with time information.
      const util = require("util");
      util.log("Node.js process object");
      
      Alt Text

v8 module

  • Showing heap data of program execution.
    const v8 = require("v8");
    const util = require("util");
    util.log(v8.getHeapStatistics());
    
    Alt Text

readline module

  • readline has createInterface.

    • We have to provide read stream and output stream in the createInterface.
      const readline = require("readline");
      const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
      });
      rl.question("Where are you living? ", (answer) => {
      rl.write(You are living in ${answer}\n);
      process.exit();
      });
      
      Alt Text

events module

  • event emtier allow us to create our own Event that we can call any time we want throughout the script's execution.
    const events = require("events");
    const emiter = new events.EventEmitter();
    emiter.on("customEvent", (message, sender) => {
    console.log("Inside the CustomEvent");
    console.log(${sender} sent you: ${message});
    });
    emiter.emit("customEvent", "Hii, there", "User");
    

Alt Text

Top comments (0)