Node.js child_process 常规使用

476 阅读1分钟

这是我参与2022首次更文挑战的第7天,活动详情查看:2022首次更文挑战

node.js child_process 使用:分为同步进程和异步进程文档传送们

异步进程

exec使用

child_process.exec(command[, options][, callback])

引入方式

const { exec } = require('child_process');

使用方式: 以执行curl为例:

exec(
      `curl -X POST "es-master:9200/_bulk?pretty" -H 'Content-Type: application/json' --data-binary "@1.txt"`,
      function (err, out, code) {
        if (err instanceof Error) throw err;
        console.log(err);
        console.log(out);
      },
    );

execFile使用

child_process.execFile(file[, args][, options][, callback])

引入方式

const { execFile } = require('child_process');

使用方式: 以执行curl为例:

// node 为文件名
execFile('node',
      function (err, out, code) {
        if (err instanceof Error) throw err;
        console.log(err);
        console.log(out);
      },
    );

spawn使用

child_process.spawn(command[, args][, options])

引入方式

const { spawn } = require('child_process');

使用方式: 以执行curl为例:

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}`);
});

同步进程

execFileSync execSync spawnSync 使用跟异步进程相差无几。根据具体实现场合去定。

持续更新~~