child_process
child_process 模块用于派生子进程,其功能类似于 Unix 系统中的 popen(3),但存在差异。该模块的核心功能主要通过 [child_process.spawn()] 函数实现:
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`输出:${data}`);
});
ls.stderr.on('data', (data) => {
console.log(`错误:${data}`);
});
ls.on('close', (code) => {
console.log(`子进程退出码:$[code]`);
});
const { exec } = require('child_process');
exec('my.bat', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
// 文件名带有空格的脚本:
const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true });
// 或:
exec('"my script.cmd" a b', (err, stdout, stderr) => {
// ...
});
除了核心 spawn 方法外,child_process 模块还提供了一系列基于 [child_process.spawn()] 或 [child_process.spawnSync()] 封装的同步与异步辅助功能。
[child_process.exec()]:派生一个 Shell 并在其中执行命令。命令执行完毕后,stdout 和 stderr 数据将传递给回调函数。
const { spawn } = require('child_process');
const grep = spawn('grep', ['ssh']);
grep.on('close', (code, signal) => {
console.log(`子进程收到信号 ${signal} 而终止`);
});
// 发送 SIGHUP 到进程
grep.kill('SIGHUP');
[child_process.execFile()]:与 [child_process.exec()] 类似,但区别在于它直接派生可执行文件,而不经过 Shell 层。
[child_process.fork()]:派生一个新的 Node.js 进程,并通过建立 IPC(进程间通信)通道调用指定模块,从而实现父进程与子进程之间的双向信息发送。
[child_process.execSync()]:作为 [child_process.exec()] 的同步版本,它会阻塞 Node.js 的事件循环直到命令执行完成。
[child_process.execFileSync()]:作为 [child_process.execFile()] 的同步版本,同样会阻塞 Node.js 的事件循环。
options.detached
在 Windows 平台上,若将 detached 选项设置为 true,子进程将在父进程退出后继续运行,并拥有独立的控制台窗口。一旦启用分离模式,便无法再将其禁用。
在非 Windows 平台中,若 detached 为 true,子进程将成为新进程组和会话的领导者。需注意,无论是否设置分离,子进程均可能在父进程退出后继续运行。
更多细节请参考 setsid(2) 手册页。
const fs = require('fs');
const { spawn } = require('child_process');
const out = fs.openSync('./out.log', 'a');
const err = fs.openSync('./out.log', 'a');
const subprocess = spawn('prg', [], {
detached: true,
stdio: [ 'ignore', out, err ]
});
subprocess.unref();
默认情况下,父进程会等待分离的子进程退出。若要防止父进程等待特定子进程,可调用 subprocess.unref() 方法。这将使父进程的事件循环排除对该子进程引用计数的跟踪,从而使父进程独立于子进程的退出状态,除非两者之间建立了 IPC 通道。
启动长时间运行的分离进程时,若未提供未连接到父进程的 stdio 配置,进程在父进程退出后将不会在后台继续运行。如果继承了父进程的 stdio,子进程将保持与控制终端的连接。
例如,对于需要忽略父进程终止的长时间运行进程,可以将父进程的 stdio 文件描述符分离并忽略:
const { spawn } = require('child_process');
const subprocess = spawn(process.argv[0], ['child_program.js'], {
detached: true,
stdio: 'ignore'
});
subprocess.unref();
若未传递信号,[ChildProcess] 对象可能会触发 'error' 事件。向已退出的子进程发送信号虽不构成错误,但可能产生不可预测的后果。
特别是,如果一个进程的 PID 被重新分配给另一个进程,发出的信号将被发送给该新进程,这可能导致意外结果。
注意,当调用 kill 函数时,发送给子进程的信号实际上可能并不会终止该进程。
'use strict';
const { spawn } = require('child_process');
const subprocess = spawn(
'sh',
[
'-c',
`node -e "setInterval(() => {
console.log(process.pid, 'is alive')
}, 500);"`
], {
stdio: ['inherit', 'inherit', 'inherit']
}
);
setTimeout(() => {
subprocess.kill(); // 不会终止 shell 中的 node 进程
}, 2000);
一旦套接字被传递给子进程,父进程便无法再跟踪套接字的销毁时机。此时连接属性将变为空。发生这种情况时,不建议继续使用相关连接。
最大连接数限制。建议子进程中的任何消息处理程序都应验证套接字是否存在,因为在发送到子进程期间连接可能会关闭。
cipher.update
使用新数据更新密码对象。如果提供了 inputEncoding 参数,其值必须为 “utf8”、“ascii” 或 “latin1”,且 data 参数必须是使用该编码的字符串。若未提供 inputEncoding,则 data 必须为 Buffer、TypedArray 或 DataView 对象。若 data 为上述对象类型,则忽略 inputEncoding 参数。
outputEncoding 指定加密数据的输出格式,可选值为 “latin1”、“base64” 或 “hex”。若指定了 outputEncoding,则返回对应编码的字符串;若未提供,则返回 Buffer 对象。
update() 方法可以被多次调用以传入新数据,直到最终调用 cipher.final() 为止。
['cipher.final()'] 用于结束密码操作并刷新缓冲区。
final() 方法在特定条件下会抛出错误。
const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
let decrypted = '';
decipher.on('readable', () => {
const data = decipher.read();
if (data)
decrypted += data.toString('utf8');
});
decipher.on('end', () => {
console.log(decrypted);
// Prints: some clear text data
});
const encrypted =
'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
decipher.write(encrypted, 'hex');
decipher.end();
const crypto = require('crypto');
const fs = require('fs');
const decipher = crypto.createDecipher('aes192', 'a password');
const input = fs.createReadStream('test.enc');
const output = fs.createWriteStream('test.js');
input.pipe(decipher).pipe(output);
返回所有剩余的解密内容。如果 outputEncoding 参数是 “latin1”、“ascii” 或 “utf8” 之一,则返回字符串;若未提供输出编码,则返回 Buffer。
一旦 final() 方法完成解密,decipher 对象便不能再用于解密数据。尝试多次调用 decipher.final() 将导致抛出错误。
const crypto = require('crypto');
const assert = require('assert');
// Generate Alice's keys...
const alice = crypto.createDiffieHellman(2048);
const aliceKey = alice.generateKeys();
// Generate Bob's keys...
const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
const bobKey = bob.generateKeys();
// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);
// OK
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
错误的冒泡和捕获
Node.js 支持多种机制来冒泡和处理应用程序运行时发生的错误。错误的报告和完全处理方式取决于错误类型及所调用 API 的风格。所有 JavaScript 错误均被视为异常,会立即生成并通过标准的 JavaScript throw 机制抛出,这些错误通常通过 try/catch 语句进行处理。
try {
const m = 1;
const n = m + z;
} catch (err) {
// 在这里处理错误。
}
任何使用 JavaScript throw 机制产生的异常都必须用 try/catch 处理,否则 Node.js 进程将立即退出。除少数例外情况外,同步 API(如不接受回调函数的阻塞方法 [fs.readFileSync])均使用 throw 报告错误。异步 API 中的错误可通过多种方式报告:大多数异步方法接受回调函数,其第一个参数为 Error 对象。若第一个参数非 null 而是 Error 实例,则表示发生了错误,需进行相应处理。
以上就是Node.js在child_process域和错误冒泡及捕获实践的详细内容,更多关于Node.js child_process错误捕获的资料请关注本站其它相关文章!