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);
- 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]);
- We can also pass arguments as a flag.
var index = process.argv.indexOf("--words") + 1; console.log(process.argv[index]);
- Write on the console using process object.
process.stdout.write("Hello"); process.stdout.write("World\n\n");
-
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); });
- In below example stop manually process.
process.stdin.on("data", (data) => { process.stdout.write(data); process.exit(); // this function call stop the process });
-
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);
- In this example console will clear before each and every print statement.
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");
- It displays data with time information.
v8 module
- Showing heap data of program execution.
const v8 = require("v8"); const util = require("util"); util.log(v8.getHeapStatistics());
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(); });
- We have to provide read stream and output stream in the createInterface.
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");
Top comments (0)