Hea*_*ray 3 file-descriptors node.js
我在理解文件描述符是什么以及我是否需要一个时有点困惑!我正在尝试在 nodejs 中生成一个进程,并将其输出直接写入输出文件。
我知道我的问题特定于 unix 系列范围之外的语言,但我相信我的问题来自我不了解系统而不是语言的某些事情。
这是我从脚本中调用的函数。我以为我可以这样称呼它
require('child_process').spawn('./my_script.bash 1>out.txt')
Run Code Online (Sandbox Code Playgroud)
虽然没有运气!我知道脚本正在执行并且正在运行。
小智 5
spawn 命令返回一个可读流,因此您需要将其通过管道传输到可写流以执行一些有用的操作。
// the filed module makes simplifies working with the filesystem
var filed = require('filed')
var path = require('path')
var spawn = require('spawn')
var outputPath = path.join(__dirname, 'out.txt')
// filed is smart enough to create a writable stream that we can pipe to
var writableStream = filed(outputPath)
var cmd = path.join(__dirname, 'my_script.bash')
var args = [] // you can option pass arguments to your spawned process
var child = spawn(cmd, args)
// child.stdout and child.stderr are both streams so they will emit data events
// streams can be piped to other streams
child.stdout.pipe(writableStream)
child.stderr.pipe(writableStream)
child.on('error', function (err) {
console.log('an error occurred')
console.dir(err)
})
// code will be the exit code of your spawned process. 0 on success, a positive integer on error
child.on('close', function (code) {
if (code !== 0) {
console.dir('spawned process exited with error code', code)
return
}
console.dir('spawned process completed correctly at wrote to file at path', outputPath)
})
Run Code Online (Sandbox Code Playgroud)
您将需要安装归档模块来运行上面的示例
npm install filed
Run Code Online (Sandbox Code Playgroud)
process.stdout 和 process.stderr 都是可写流,因此您也可以将生成的命令的输出直接通过管道传输到控制台
var path = require('path')
var spawn = require('spawn')
var cmd = path.join(__dirname, 'my_script.bash')
var args = [] // you can option pass arguments to your spawned process
var child = spawn(cmd, args)
// child is a stream so it will emit events
child.stderr.pipe(process.stderr)
child.stdout.pipe(process.stderr)
child.on('error', function (err) {
console.log('an error occurred')
console.dir(err)
})
// code will be the exit code of your spawned process. 0 on success, a positive integer on error
child.on('close', function (code) {
if (code !== 0) {
console.dir('spawned process exited with error code', code)
return
}
console.dir('spawned process completed correctly at wrote to file at path', outputPath)
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3157 次 |
最近记录: |