top
upGrad KnowledgeHut SkillFest Sale!

Search

Node JS Tutorial

Node.js comes with a child process module, which helps to run other processes in the current environment i.e. it can be used to communicate with other processes. Let’s understand this with an example. App1:  Create a new file exec.js and import child_process module. const cp = require(“child_process”); The child process has a method exec to open another process. cp.exec(“open http://www.google.com”); run node exec And observe that google page is opened. Imagine if we invoke a process that returns data then we can grab that data as well. cp.exec(“ls”, (err, data) => {   if (err) { throw err; }  Console.log(data);  }); In step 5, we are listing down all the files because of ls command. If we spell it wrongly say listFiles then we get an error saying listFiles: command not found. Error object has all the stack trace content. If we want just the brief note on an error then we can rely on 3rd parameter of the callback ‘stderr’. cp.exec(“ls”, (err, data, stderr) => { console.log(stderr);  }); So, cp.exec can execute any process. From the previous example, we were running node readStream. Even this can be executed from the child process exec command. cp.exec(“node  readStream”, …); Exec is for invoking the other processes and capturing their output. This happens in a synchronous way. To handle the async way, we need to understand the spawn method of the child process.  During HandlingData module, we create a node.js app which displays a set of questions. It starts displaying the first question and on answering it, we are been asked the second question and so on until all questions are answered. This app was working in an async way and reacting to user inputs.  Lets copy that file and rename to question.js App2:  lets create spawn.js file and import child_process. const cp = require(“child_process”); Spawn the question app using spawn method of child process. const questionApp = cp.spawn(“node”, [“questions.js”]); Also, let’s listen to the stdout of the question app and populate it. questionApp.stdout.on(“data”, data => { console.log(`from question app: ${data}`);  }); Run the node spawn.js  Observe that questionApp is executed and first question is displayed. But the terminal is not taking any inputs. Let's capture the input from the current terminal and send it to the question app. Process.stdin.on(“data”, data => { questionApp.stdin.write(`${data}` \n’);  }); When question app is closed, lets close our current app as well by listening to close event. questionApp.on(“close”, () => {  console.log(“questionApp process is exited”);  process.exit();  }); Run node spawn.js Terminal should display each question after another on answering from question app. On completion of all questions, process has to exit.  constcp = require("child_process");  constquestionApp = cp.spawn("node", ["questions.js"]);  questionApp.stdout.on("data", data=> {  console.log(`from the question app: ${data}`);  });  process.stdin.on("data", data=> {  questionApp.stdin.write(`${data}\n\n`);  });  questionApp.on("close", () => {  console.log(`questionApp process exited`);  process.exit();  });  Output:  from the question app:   What is your name? >  Trainer  from the question app:   What would you rather be doing? >  Training  from the question app:   What is your preferred programming language? >  Javascript  from the question app:   Training Trainer, Javascript is awesome!  questionApp process exited
logo

Node JS Tutorial

Child Process

Node.js comes with a child process module, which helps to run other processes in the current environment i.e. it can be used to communicate with other processes. 

Let’s understand this with an example. 

App1:  

  • Create a new file exec.js and import child_process module. 
  • const cp = require(“child_process”); 
  • The child process has a method exec to open another process. 
  • cp.exec(“open http://www.google.com”); 
  • run node exec 
  • And observe that google page is opened. 
  • Imagine if we invoke a process that returns data then we can grab that data as well. 
cp.exec(“ls”, (err, data) => { 
 if (err) { throw err; } 
Console.log(data); 
}); 
  • In step 5, we are listing down all the files because of ls command. If we spell it wrongly say listFiles then we get an error saying listFiles: command not found. 
  • Error object has all the stack trace content. If we want just the brief note on an error then we can rely on 3rd parameter of the callback ‘stderr’. 
  • cp.exec(“ls”, (err, data, stderr) => { 
console.log(stderr); 
}); 
  • So, cp.exec can execute any process. From the previous example, we were running node readStream. Even this can be executed from the child process exec command. 
  • cp.exec(“node  readStream”, …); 

Exec is for invoking the other processes and capturing their output. This happens in a synchronous way. To handle the async way, we need to understand the spawn method of the child process.  

During HandlingData module, we create a node.js app which displays a set of questions. It starts displaying the first question and on answering it, we are been asked the second question and so on until all questions are answered. This app was working in an async way and reacting to user inputs.  

Lets copy that file and rename to question.js 

App2:  

  • lets create spawn.js file and import child_process. 
  • const cp = require(“child_process”); 
  • Spawn the question app using spawn method of child process. 
  • const questionApp = cp.spawn(“node”, [“questions.js”]); 
  • Also, let’s listen to the stdout of the question app and populate it. 
  • questionApp.stdout.on(“data”, data => { 
console.log(`from question app: ${data}`); 
}); 
  • Run the node spawn.js  
  • Observe that questionApp is executed and first question is displayed. 
  • But the terminal is not taking any inputs. 
  • Let's capture the input from the current terminal and send it to the question app. 
  • Process.stdin.on(“data”, data => { 
questionApp.stdin.write(`${data}` \n’); 
}); 
  • When question app is closed, lets close our current app as well by listening to close event. 
questionApp.on(“close”, () => { 
console.log(“questionApp process is exited”); 
process.exit(); 
}); 
  • Run node spawn.js 
  • Terminal should display each question after another on answering from question app. On completion of all questions, process has to exit.  
constcp = require("child_process"); 
constquestionApp = cp.spawn("node", ["questions.js"]); 
questionApp.stdout.on("data", data=> { 
console.log(`from the question app: ${data}`); 
}); 
process.stdin.on("data", data=> { 
questionApp.stdin.write(`${data}\n\n`); 
}); 
questionApp.on("close", () => { 
console.log(`questionApp process exited`); 
process.exit(); 
}); 
Output: 
from the question app: 
 What is your name? > 
Trainer 
from the question app: 
 What would you rather be doing? > 
Training 
from the question app: 
 What is your preferred programming language? > 
Javascript 
from the question app: 
 Training Trainer, Javascript is awesome! 
questionApp process exited 

Leave a Reply

Your email address will not be published. Required fields are marked *

Suggested Tutorials

JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. JavaScript was first known as LiveScript. Later on, Netscape changed its name to JavaScript because of its popularity and the excitement generated by it. JavaScript is lightweight and most commonly used as a part of web pages supported by most web browsers like Chrome, Internet Explorer, Opera, Safari, Edge, and Firefox.
JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. Jav...

Read More

Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introduced by Google corporation in 2012 and was considered to be one of the most promising among JavaScript frameworks. It was written completely in JavaScript to separate an application’s logic from DOM manipulation, aiming at dynamic page updates. Angular introduced many powerful features enabling the developer to effortlessly create rich and single-page applications.Topics CoveredThis Angular tutorial will span over eight modules, each module covering numerous individual aspects that you need to gain complete information about Angular. This set of modules serves as an Angular tutorial for beginners along with experienced IT professionals.Here are the topics that will be covered in the Angular tutorial:Get started with Angular.Learn the basics of Angular.Know what Angular Directives.Get an idea of Component Inputs and Outputs of Angular.Know about Forms in Angular.About Services in Angular.Pipes in Angular.HTTP, Routing and Building in Angular.Who can benefit from this tutorial?This Angular tutorial will be helpful to IT professionals such as:Software Developers, Web Application Programmers and IT Professionals Software Architects and Testing Professionals Career aspirants in web development
Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introdu...

Read More

USEFUL LINKS