2016-09-06 336 views
1

我想找到一些好的庫來使用nodejs執行shell腳本命令(例如:rm,cp,mkdir等)。最近沒有關於可能軟件包的明確文章。我讀了很多關於exec-sync的信息。但有人說它已被棄用。真的,我迷路了,找不到任何東西。我嘗試安裝exec-sync,但收到以下錯誤:使用nodejs執行shell腳本命令

npm ERR! [email protected] install: `node-gyp rebuild` 
npm ERR! Exit status 1 
npm ERR! 
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'. 

您有什麼建議嗎?

+0

嘗試FS-EXTRA:https://www.npmjs.com/package/fs-extra – datafunk

回答

3

您可以簡單地使用節點Child Process核心模塊,或者至少使用它來構建您自己的模塊。

Child Process

The child_process module provides the ability to spawn child processes in a manner that is similar, but not identical, to popen(3). This capability is primarily provided by the child_process.spawn() function:

特別是exec()方法。

child_process.exec()

spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.

這裏是來自文檔的示例。

Spawns a shell then executes the command within that shell, buffering any generated output.

const exec = require('child_process').exec; 
exec('cat *.js bad_file | wc -l', (error, stdout, stderr) => { 
    if (error) { 
    console.error(`exec error: ${error}`); 
    return; 
    } 
    console.log(`stdout: ${stdout}`); 
    console.log(`stderr: ${stderr}`); 
}); 
+0

是否有高管的同步版本? –

+0

'child_process.execSync(command [,options])';) – DavidDomain