Process Object

The process object is available globally meaning that it can be accessed from anywhere in the code. It allows us to fetch information regarding the current process instance; information such as environmental variables, path, stdin, and stdout.

console.log(process.argv);

Save this code as processdemo.js. To run:

$ node processdemo.js

This code outputs the parameters used when the process starts. It's output is as follows:

[ '/usr/bin/node', '/Users/testing/exercises/processdemo.js' ]

If I run the command with parameters:

$ node processdemo.js id name

The output will be:

[ '/usr/bin/node', '/Users/testing/exercises/processdemo.js' ,'id','name']

To get an individual parameter, simply print the specific element in the process.argv array by it's index

console.log(process.argv[3]);

will output:

name

process.stdout.write prints to the terminal. process.stdin.on adds a listener event. See the example below.

var question = "Say something?";
var answer = "";

function prompt() {
  process.stdout.write(`\n ${question}: `);
}

process.stdin.on('data', function(data) {
  answer = data.toString().trim();
  process.exit();
});

process.on('exit', function() {
  process.stdout.write(`\nYou said ${answer}\n`);
});

prompt();

In this program, we begin from the call to prompt() function at the bottom. prompt() function prints the question to the terminal using stdout.write function(). process.stdin.on('data'...) is an event listener that listens for data. Once you type something and hit return, process.on('exit'..) function is called. It prints your response to the question.