nodejs 呼叫系統命令/shell檔案/可執行檔案
阿新 • • 發佈:2022-04-06
- child_process.exec(command[, options][, callback]) 啟動子程序來執行shell命令,可以通過回撥引數來獲取指令碼shell執行結果
- child_process.execfile(file[, args][, options][, callback])與exec型別不同的是,它執行的不是shell命令而是一個可執行檔案
- child_process.spawn(command[, args][, options])僅僅執行一個shell命令,不需要獲取執行結果
- child_process.fork(modulePath[, args][, options])可以用node執行的.js檔案,也不需要獲取執行結果。fork出來的子程序一定是node程序
// ******************系統命令****************** var spawn = require('child_process').spawn; free = spawn('free', ['-m']); // 捕獲標準輸出並將其列印到控制檯 free.stdout.on('data', function (data) { console.log('standard output:\n' + data); }); // 捕獲標準錯誤輸出並將其列印到控制檯 free.stderr.on('data', function (data) { console.log('standard error output:\n' + data); }); // 註冊子程序關閉事件 free.on('exit', function (code, signal) { console.log('child process eixt ,exit:' + code); }); // ******************系統命令****************** var exec = require('child_process').exec; var cmdStr = "ls"; exec(cmdStr, function(err,stdout,stderr){ if(err) { console.log('error:'+stderr); } else { console.log('args stdout:'+stdout); } }); //************* 呼叫shell檔案 ************ // chmod 777 // shell.sh: // #!/bin/sh // echo "$(pwd)" var execfile = require('child_process').exec; execfile("./shell.sh",function(err, stdout,stderr){ if(err) { console.log('error:'+stderr); } else { console.log('args stdout:'+stdout); } }); //************* 呼叫可執行檔案 ************ var cp = require("child_process"); cp.execFile("colmap",["gui"],function(err,stdout,stderr){ if(err){ // console.error(err); console.log('error:'+err); } console.log("stdout:",stdout) console.log("stderr:",stderr); });