nodeJS exec does not work for “cd ” shell cmd

后端 未结 3 1838
忘掉有多难
忘掉有多难 2021-02-05 01:04
var sys = require(\'sys\'),
    exec = require(\'child_process\').exec;

exec(\"cd /home/ubuntu/distro\", function(err, stdout, stderr) {
        console.log(\"cd: \" +          


        
相关标签:
3条回答
  • 2021-02-05 02:05

    Rather than call exec() multiple times. Call exec() once for multiple commands

    Your shell IS executing cd but it's just that each shell throws away it's working directory after it's finished. Hence you're back at square one.

    In your case, you don't need to call exec() more than once. You can make sure your cmd variable contains multiple instructions instead of 1. CD will work in this case.

    var cmd =  `ls
    cd foo
    ls`
    
    var exec =  require('child_process').exec;
    
    exec(cmd, function(err, stdout, stderr) {
            console.log(stdout);
    })
    

    Note: This code should work on Linux but not Windows. See here

    0 讨论(0)
  • 2021-02-05 02:07

    Each command is executed in a separate shell, so the first cd only affects that shell process which then terminates. If you want to run git in a particular directory, just have Node set the path for you:

    exec('git status', {cwd: '/home/ubuntu/distro'}, /* ... */);
    

    cwd (current working directory) is one of many options available for exec.

    0 讨论(0)
  • 2021-02-05 02:08

    It is working. But then it is throwing the shell away. Node creates a new shell for each exec.

    Here are options that can help: http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

    0 讨论(0)
提交回复
热议问题