【问题标题】:executing multiple terminal commands in nodejs code在nodejs代码中执行多个终端命令
【发布时间】:2014-05-02 06:31:38
【问题描述】:

我正在尝试通过节点脚本执行多个终端命令

我有一个像 smaple.sh 这样的 shell 脚本,它运行良好

cd ~/Desktop
find -type f -printf '%T+\t%p\n' | sort -n

我正在尝试在节点脚本中执行上述终端命令

        var command = ' cd ~/Desktop'
        command +=' find -type f -printf %T+\\t%p\\n | sort -n' 

 exec(command, function (error, stdout, stderr) {

});

在执行上述代码时,一无所获。 首先我需要更改目录然后执行第二个命令

find -type f -printf %T+\\t%p\\n | sort -n

【问题讨论】:

    标签: node.js shell


    【解决方案1】:

    使用您当前的代码,node.js 正在尝试执行以下操作:

    cd ~/Desktop find -type f -printf %T+\\t%p\\n | sort -n

    如果你尝试在节点之外运行它,你会得到相同的结果。

    您需要使用&&; 来区分命令,如下所示:

    var command = ' cd ~/Desktop &&'
    command +=' find -type f -printf %T+\\t%p\\n | sort -n' 
    
    exec(command, function (error, stdout, stderr) {
    
    });
    

    也许更优雅的方法:

    var commands = [];
    commands.push('cd ~/Desktop');
    commands.push('find -type f -printf %T+\\t%p\\n | sort -n');
    
    var command = commands.join(' && ');
    
    exec(command, function (error, stdout, stderr) {
    
    });
    

    【讨论】:

    • 我得到exec error: Error: Command failed: execvp(): No such file or directory 但我已经有那个目录了
    • 在终端上执行你的代码时它工作正常。但是使用 exec 我得到了上述错误
    猜你喜欢
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 2015-05-27
    • 2016-12-06
    • 2014-07-03
    • 1970-01-01
    • 2020-01-29
    相关资源
    最近更新 更多