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

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

構文
const { execSync } = require('child_process’)
同期実行させたい場合、execSync を利用します。
非ストリーム形式でシェルスクリプトを同期実行します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const { execSync } = require('child_process')
const stdout = execSync('ls -l test.txt')
console.log(`stdout: ${stdout.toString()}`)
console.log('arkgame.com')
const { execSync } = require('child_process') const stdout = execSync('ls -l test.txt') console.log(`stdout: ${stdout.toString()}`) console.log('arkgame.com')
const { execSync } = require('child_process')

const stdout = execSync('ls -l test.txt')
console.log(`stdout: ${stdout.toString()}`)
console.log('arkgame.com')

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ node execSync.js
stdout: -rwxr-xr-x 1 xxx xxx 21166 Nov 22 01:02 test.txt
arkgame.com
$ node execSync.js stdout: -rwxr-xr-x 1 xxx xxx 21166 Nov 22 01:02 test.txt arkgame.com
$ node execSync.js
stdout: -rwxr-xr-x 1 xxx xxx 21166 Nov 22 01:02 test.txt

arkgame.com

 

IT

Posted by arkgame