パイプからファイルへ

パイプからファイルへ

ファイル記述子が何であるか、必要かどうかを理解するのに少し混乱があります! Node.jsでプロセスを作成し、その出力を出力ファイルに直接書き込もうとします。

私は私の問題がUnixシリーズの範囲外の言語に固有であることを知っていますが、私の問題は、言語ではなくシステムに関する何かを理解していないことに起因すると思います。

これ私がスクリプトから呼び出す関数です。こう呼んでもいいと思いました。

require('child_process').spawn('./my_script.bash 1>out.txt')

しかし幸運はありません!スクリプトが実行され実行中であることがわかります。

ベストアンサー1

generateコマンドは読み取り可能なストリームを返すため、便利な操作を実行するには書き込み可能なストリームにパイプする必要があります。

パイプからファイルへ

// 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)
})

上記の例を実行するには、アーカイブモジュールをインストールする必要があります。

npm install filed

stdoutとstderrによるパイプ

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

おすすめ記事