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:
cp.exec(“ls”, (err, data) => { if (err) { throw err; } Console.log(data); });
console.log(stderr); });
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:
console.log(`from question app: ${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(); });
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
JavaScript is a dynamic computer programming language for the web. Jav...
Introduction: Angular (What is Angular?)Angular was formerly introdu...
Leave a Reply
Your email address will not be published. Required fields are marked *