nodeJS exec does not work for “cd ” shell cmd

后端 未结 3 1836
忘掉有多难
忘掉有多难 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

提交回复
热议问题