How to use the spawn function from child_process

Find comprehensive JavaScript child_process.spawn code examples handpicked from public code repositorys.

child_process.spawn() is a method in Node.js that launches a new process with the given command and arguments.

21
22
23
24
25
26
27
28
29
30
/**
 * Build the Jekyll Site
 */
gulp.task('jekyll-build', function (done) {
    browserSync.notify(messages.jekyllBuild);
    return cp.spawn('jekyll', ['build'], {stdio: 'inherit'})
        .on('close', done);
});

/**
fork icon87
star icon224
watch icon28

+ 13 other calls in file

3
4
5
6
7
8
9
10
11
12
const postcss = require('postcss');
const autoprefixer = require('autoprefixer');
const postcssSafeParser = require('postcss-safe-parser');
const postcssScssParser = require('postcss-scss');

const subprocess = childProcess.spawn('npx', ['browserslist@latest', '--update-db'], {cwd: __dirname, stdio: 'ignore'});
subprocess.unref();
subprocess.on('error', () => {});

(async () => {
fork icon82
star icon669
watch icon27

+ 7 other calls in file

How does child_process.spawn work?

child_process.spawn() is a Node.js method that starts a new process and runs a command in it. It returns a ChildProcess object, which allows communication between the parent and child process through standard input/output and error streams. The method takes a command as a string, an optional array of arguments, and options such as the working directory and environment variables.

11
12
13
14
15
16
17
18
19
20
return (async () => {
	let users = new Map();

	let git = new Promise((resolve, reject) => {
		try {
			const child = CHILD_PROCESS.spawn('git', ['shortlog', '-sn', '--all']);

			let sout = "";
			child.stdout.setEncoding('utf8');
			child.stdout.on('data', (data) => {
fork icon342
star icon0
watch icon99

+ 4 other calls in file

9
10
11
12
13
14
15
16
17
18
19
20
const {spawn} = require("child_process")


let pythonProcess


if (PRODUCTION) {
    // pythonProcess = spawn(`${path}/cpython/server.exe`, {stdio: "ignore"})
} else {
    pythonProcess = spawn("python", [`${path}/server.py`], {stdio: "ignore"})
}

fork icon41
star icon416
watch icon21

+ 7 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const { spawn } = require("child_process");

const ls = spawn("ls", ["-lh", "/usr"]);

ls.stdout.on("data", (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on("data", (data) => {
  console.error(`stderr: ${data}`);
});

ls.on("close", (code) => {
  console.log(`child process exited with code ${code}`);
});

In this example, spawn takes two arguments: the command to run (ls) and an array of arguments to pass to the command (['-lh', '/usr']). The ls command is executed with the specified arguments in a new child process, and its output is printed to the console using event listeners on the stdout and stderr streams. Finally, the close event is triggered when the child process exits, and the exit code is printed to the console.

181
182
183
184
185
186
187
188
189
190
console.log('Executing script inside Emacs...');
if (argv.verbose == 4)
  console.log('[DEBUG] emacs ' + cmd.join(' '));

setup_env();
let proc = child_process.spawn(cli_args(cmd), { stdio: 'inherit', shell: true });

proc.on('close', function (code) {
  if (code == 0) {
    resolve(code);
fork icon7
star icon63
watch icon2

246
247
248
249
250
251
252
253
254
255
        appletContents = appletContents.replaceAll(`cache.`, `cache_redis.`);
    }
}
fs.writeFileSync(`${APPLET_FOLDER}/${name}/${manifest.fileName.replace(".star", ".tmp.star")}`, appletContents);

const renderCommand = spawn(`pixlet`, ['render', `${APPLET_FOLDER}/${name}/${manifest.fileName.replace(".star", ".tmp.star")}`, ...configValues, '-o', `/tmp/${device}-${manifest.fileName}.webp`], { timeout: 10000 });

renderCommand.stdout.on('data', (data) => {
    outputError += data
})
fork icon2
star icon3
watch icon0

10
11
12
13
14
15
16
17
18
19
// logger.debug(`Launching ${hash} with arguments ${javaPath} ${javaArgs.join(' ')}`);

const id = generateIdFor(instances);

const controller = new AbortController();
const currentProcess = spawn(
	javaPath, javaArgs,
	{
		encoding: 'utf8',
		cwd: options.cwd || process.cwd,
fork icon0
star icon2
watch icon0

75
76
77
78
79
80
81
82
83

var summary;
var transcript = [];
var srt = fs.readFileSync('sub.vtt', 'utf8');
let inputtxt = vttToPlainText(srt);
const childPython = spawn('python', ['summary.py', `${inputtxt}`]);
childPython.stdout.on('data', (data) => {
    summary = data.toString();
});
fork icon1
star icon0
watch icon1

+ 3 other calls in file

59
60
61
62
63
64
65
66
67
68
}


function launchNow (sd, plat) {
    console.log(sd.command + " " + sd.args.join(" "));
    const proc = spawn(sd.command, sd.args, sd.options);
    proc.on("error", function (err) {
        console.log(err);
        sd = alternateCommand(sd, plat);
        if(sd) {
fork icon0
star icon1
watch icon1

664
665
666
667
668
669
670
671
672
673
674
675


/** Start Unit tests */
exports.startUnitTest = async () => {
    console.log("Starting unit test...");
    const npm = /^win/.test(process.platform) ? "npm.cmd" : "npm";
    const child = childProcess.spawn(npm, ["run", "jest-backend"]);


    child.stdout.on("data", (data) => {
        console.log(data.toString());
    });
fork icon0
star icon0
watch icon1

83
84
85
86
87
88
89
90
91
92
93
}


module.exports = {
    createBuyInvoice : asyncHandler(async (req , res , next) => {
        var results = []
        const childPython = spawn('python' , ['pdfreader.py' , req.file.path])
        childPython.stdout.on('data' , (data) => {
            console.log(`data: ${data}`)
            fs.createReadStream(__dirname +'/first_table.csv').pipe(csv()).on('data' , (response) => {
                results.push(response)
fork icon0
star icon0
watch icon1

156
157
158
159
160
161
162
163
164
165
166
}


async function doReboot() {
  setAdminStatus("rebooting in 5 seconds");
  setTimeout(() => {
    spawn("sudo", ["reboot"]);
  }, 7 * 1000);
  await sleep(5 * 1000);
  setAdminStatus("done");
}
fork icon0
star icon0
watch icon2

7
8
9
10
11
12
13
14
15
16
17


app.use(bodyParser.json());
app.post('/api/product', (req, res,next) => {
    var dataToSend;
    console.log("Request body: ", req.body);
    const python = spawn('python', ['scraper.py', req.body.url]);
    // collect data from script
    python.stdout.on('data', function (data) {
        console.log('Pipe data from python script ...');
        dataToSend = data.toString();
fork icon0
star icon0
watch icon1

251
252
253
254
255
256
257
258
259
260
function pushToPythonProcess(uploadFileName,filetype)
{
   const { spawn } = require('child_process');
   console.log(uploadFileName);
  
       const pyProg = spawn('python3', ['/home/foxtrot/foxtrot_ml/processMasterCSV.py',filetype,uploadFileName]);
       let result = '';
       pyProg.stdout.on('data', function(data) {
               result += data.toString();
           console.log(data.toString());
fork icon0
star icon0
watch icon1

152
153
154
155
156
157
158
159
160
161
app.post("/api/config", async (req,res) => {
    await fs.writeFile(path.resolve(path.join(__dirname, "/../config.json")), JSON.stringify(req.body, null, 4))
    res.status(200).json({status: "OK"})
    setTimeout(() => {
        process.on("exit", function () {
            cp.spawn(process.argv.shift(), process.argv, {
                cwd: process.cwd(),
                detached : true,
                stdio: "inherit"
            });
fork icon0
star icon0
watch icon1

22
23
24
25
26
27
28
29
30
31
}

const rootPath = workspaceFolders[0].uri.fsPath;
const command = 'php';
const args = ['artisan', 'waka:tradauto', 'get', escapeShellArg(selectedText)];
const getProcess = spawn(command, args, { cwd: rootPath });

let stdout = '';
getProcess.stdout.on('data', (data) => {
  stdout += data.toString();
fork icon0
star icon0
watch icon1

+ 2 other calls in file

4
5
6
7
8
9
10
11
12
13
constructor(workspaceRoot) {
  this.workspaceRoot = workspaceRoot;
}

run(command, args, onData, onError, onClose) {
  const childProcess = spawn(command, args, {
    cwd: this.workspaceRoot,
  });

  childProcess.stdout.on('data', onData);
fork icon0
star icon0
watch icon1

117
118
119
120
121
122
123
124
125
126
let cloudPush;

if (!fs.existsSync(`./amplify/.config/local-env-info.json`)) {
  // init and then push

  cloudPush = spawn(amplify, ['init', '--amplify', PROJECT_CONFIG, '--providers', PROVIDER_CONFIG, '--yes'], {
    cwd: process.cwd(),
    env: process.env,
    stdio: 'inherit',
  });
fork icon0
star icon0
watch icon1

+ 2 other calls in file

66
67
68
69
70
71
72
73
74
75
global.fname = fname;
const sql = `SELECT * FROM mytable WHERE id = ${id}`;
connection.query(sql, (err, result) => {
  if (err) throw err;
  result.map((item) => {
    const pythonProcess = spawn("python", ["Python File/main.py"]);
    global.mainPythonProcess = pythonProcess;
    pythonProcess.stdin.write(item.data.toString('base64') + "\n");
    pythonProcess.stdin.write(id + "\n");
    pythonProcess.stdin.write(method + "\n");
fork icon0
star icon0
watch icon1

+ 2 other calls in file

14
15
16
17
18
19
20
21
22
23
  if (withBreak || argv["break"]) withBreak = true
  nodeargs.push(`--inspect${withBreak ? "-brk" : ""}=${argv["inspect"]}`)
}
else withBreak = false
console.log(`\x1b[32m[monitor] Start process${withBreak ? " (in break mode)" : ""}\x1b[0m`)
current = child_process.spawn(
  "node",
  [
    "--require=" + require.resolve("source-map-support/register"),
    "--enable-source-maps",
fork icon0
star icon0
watch icon1