-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchildProcesses.js
More file actions
83 lines (63 loc) · 2.16 KB
/
childProcesses.js
File metadata and controls
83 lines (63 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//Child Processes Module
//The child_process module provides the ability to spawn child processes in a manner that is similar, but not identical, to popen(3)
const exec = require("child_process");
console.log(exec);
//Execution Examples - Asynchronously Synchronous
exec.exec("start chrome http://www.google.com"); //Open URL in Chrome
exec.exec("cmd"); //Opens instance of command prompt
//List directories and then logs response - Linux
exec.exec("df", (err, stdout) => {
if (err) throw err;
console.log(stdout);
});
//List directories and then logs response - Linux
exec.exec("ls", (err, stdout) => {
if (err) throw err;
console.log(stdout);
});
//List directories and then logs response - Windows
// exec.exec("dir", (err, stdout) => {
// if (err) throw err;
// console.log(stdout);
// });
//Gets Git version and then logs response
exec.exec("git --version", (err, stdout) => {
if (err) throw err;
console.log(stdout);
});
//Gets Node version and then logs response
exec.exec("node -v", (err, stdout) => {
if (err) throw err;
console.log(stdout);
});
//Gets npm version and then logs response
exec.exec("npm -v", (err, stdout) => {
if (err) throw err;
console.log(stdout);
//process.exit();
});
//Spawn Examples - Spawn Multiple Child Process Executions
const spawn = require("child_process");
let cp = spawn.spawn("node", ["spawnExample"]);
let cpTwo = spawn.spawn("node", ["childEmitterOne"]);
//Listener for data event
cp.stdout.on("data", data => {
console.log(`STDOUT Child Process: ${data.toString().trim()}`);
});
cpTwo.stdout.on("data", data => {
console.log(`Event Emitter: ${data.toString().trim()}`);
});
//Listener for close event
cp.on("close", () => {
console.log("Child Process One has ended.");
});
cpTwo.on("close", () => {
console.log("Event Emitter has stopped");
process.exit(); //Exit parent process
});
//Close the Child Process and Stop the Event Emitter - Stop logic must be held in the Child Process
setTimeout(() => {
cp.stdin.write("STOP");
cpTwo.stdin.write("STOP");
}, 4000);
//The order of child processes declaration does not guarantee the order or frequency of execution