Node.js spawn 非同期実行 シェルスクリプトを実行するサンプル

環境
Windows 10 Home 64bit
node v16.17.0
npm 8.15.0

構文
const { spawn } = require('child_process’)
大きいデータを扱う場合、ストリーム形式である spawnを利用します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const { spawn } = require('child_process')
const childProcess = spawn('cat', ['test.txt'])
console.log('process id:' + process.pid)
console.log('child process id:' + childProcess.pid)
childProcess.stdout.on('data', (chunk) => {
console.log(new Date())
console.log(chunk.length)
})
const { spawn } = require('child_process') const childProcess = spawn('cat', ['test.txt']) console.log('process id:' + process.pid) console.log('child process id:' + childProcess.pid) childProcess.stdout.on('data', (chunk) => { console.log(new Date()) console.log(chunk.length) })
const { spawn } = require('child_process')

const childProcess = spawn('cat', ['test.txt'])

console.log('process id:' + process.pid)
console.log('child process id:' + childProcess.pid)

childProcess.stdout.on('data', (chunk) => {
  console.log(new Date())
  console.log(chunk.length)
})

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ node spawn.js
process id:44066
child process id:44093
2023-11-21T17:20:48.073Z
8192
2023-11-21T17:20:48.076Z
8192
2023-11-21T17:20:48.076Z
4782
$ node spawn.js process id:44066 child process id:44093 2023-11-21T17:20:48.073Z 8192 2023-11-21T17:20:48.076Z 8192 2023-11-21T17:20:48.076Z 4782
$ node spawn.js 
process id:44066
child process id:44093
2023-11-21T17:20:48.073Z
8192
2023-11-21T17:20:48.076Z
8192
2023-11-21T17:20:48.076Z
4782

 

IT

Posted by arkgame