node.js 同步执行系统命令
IT技术
javascript
command
node.js
exec
sync
2021-01-21 16:49:17
6个回答
请参阅execSync库。
使用node-ffi相当容易。我不会推荐用于服务器进程,但对于一般的开发实用程序,它可以完成工作。安装库。
npm install node-ffi
示例脚本:
var FFI = require("node-ffi");
var libc = new FFI.Library(null, {
"system": ["int32", ["string"]]
});
var run = libc.system;
run("echo $USER");
[编辑 2012 年 6 月:如何获得标准输出]
var lib = ffi.Library(null, {
// FILE* popen(char* cmd, char* mode);
popen: ['pointer', ['string', 'string']],
// void pclose(FILE* fp);
pclose: ['void', [ 'pointer']],
// char* fgets(char* buff, int buff, in)
fgets: ['string', ['string', 'int','pointer']]
});
function execSync(cmd) {
var
buffer = new Buffer(1024),
result = "",
fp = lib.popen(cmd, 'r');
if (!fp) throw new Error('execSync error: '+cmd);
while(lib.fgets(buffer, 1024, fp)) {
result += buffer.readCString();
};
lib.pclose(fp);
return result;
}
console.log(execSync('echo $HOME'));
node.js 中有一个出色的流量控制module,称为asyncblock。如果将代码包装在函数中适合您的情况,则可以考虑以下示例:
var asyncblock = require('asyncblock');
var exec = require('child_process').exec;
asyncblock(function (flow) {
exec('node -v', flow.add());
result = flow.wait();
console.log(result); // There'll be trailing \n in the output
// Some other jobs
console.log('More results like if it were sync...');
});
这是不可能的Node.js,都child_process.spawn
和child_process.exec
从地面建是异步。
详情见:https : //github.com/ry/node/blob/master/lib/child_process.js
如果你真的想要这个阻塞,那么把之后需要发生的所有事情都放在回调中,或者构建你自己的队列来以阻塞的方式处理这个,我想你可以使用Async.js来完成这个任务。
或者,如果您有太多时间可以花,可以自行在 Node.js 中进行破解。
其它你可能感兴趣的问题