出力は 1 つのファイルへ書き込み
const fs = require("fs")
const cp = require("child_process")
fs.writeFileSync(
"out.js",
`
const key = Math.random().toString(36).slice(2, 4)
const setNext = n => {
setTimeout(() => {
console.log(key, n)
if (n < 3) setNext(n + 1)
}, 2000)
}
setNext(0)
`
)
const stream = fs.createWriteStream("out.log")
const s1 = cp.fork("out.js", { stdio: "pipe" })
const s2 = cp.fork("out.js", { stdio: "pipe" })
s1.stdout.pipe(stream)
s2.stdout.pipe(stream)
結果は
zo 0
os 0
zo 1
os 1
zo 2
os 2
zo 3
最後の 3 が 1 つだけ
pipe のデフォルトは readstream が close したときに writestream も閉じるので先に終わったほうが終わったタイミングでスクリプトが終了してしまう
pipe のオプションで end を false にすると自動で閉じられない
s1.stdout.pipe(stream, { end: false })
s2.stdout.pipe(stream, { end: false })
あとから pipe してもいいので 1 つの writestream を使いまわして何度か実行もできる
const fs = require("fs")
const cp = require("child_process")
fs.writeFileSync(
"out.js",
`
const key = Math.random().toString(36).slice(2, 4)
const setNext = n => {
setTimeout(() => {
console.log(key, n)
if (n < 2) setNext(n + 1)
}, 2000)
}
setNext(0)
`
)
const stream = fs.createWriteStream("out.log")
const write = n => {
const s = cp.fork("out.js", { stdio: "pipe" })
s.stdout.pipe(stream, { end: false })
if (n < 3) s.stdout.once("close", write.bind(null, n + 1))
}
write(0)
xi 0
xi 1
xi 2
if 0
if 1
if 2
p9 0
p9 1
p9 2
c0 0
c0 1
c0 2