在node.js中执行并获取shell命令的输出 [英] Execute and get the output of a shell command in node.js

查看:1199
本文介绍了在node.js中执行并获取shell命令的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在node.js中,我想找到一种方法来获取Unix终端命令的输出.有什么办法吗?

In a node.js, I'd like to find a way to obtain the output of a Unix terminal command. Is there any way to do this?

function getCommandOutput(commandString){
    // now how can I implement this function?
    // getCommandOutput("ls") should print the terminal output of the shell command "ls"
}

推荐答案

这就是我现在正在工作的项目中这样做的方式.

Thats the way I do it in a project I am working now.

var exec = require('child_process').exec;
function execute(command, callback){
    exec(command, function(error, stdout, stderr){ callback(stdout); });
};

示例:检索git用户

module.exports.getGitUser = function(callback){
    execute("git config --global user.name", function(name){
        execute("git config --global user.email", function(email){
            callback({ name: name.replace("\n", ""), email: email.replace("\n", "") });
        });
    });
};

这篇关于在node.js中执行并获取shell命令的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆