在 Node.js 中使用 && 运算符在一行中执行两个命令时出错

问题描述 投票:0回答:1

同时

cd ./tools/darwin/ && ./adb
在我的 Mac 终端上工作,

我的node.js应用程序与这段代码

const CHANGE_DIRECTORY_COMMAND = "cd ./tools/darwin/"
const EXECUTE_ADB_COMMAND = "./adb"

if(platform === "darwin") {
  exec(`${CHANGE_DIRECTORY_COMMAND} && ${EXECUTE_ADB_COMMAND}`, (error, stdout, stderr) => {
    if (error) {
      console.error(`Error executing the adb file: ${error}`);
      return;
    }

    if (stdout) {
      console.log(`Standard output: ${stdout}`);
    }

    if (stderr) {
      console.error(`Standard error: ${stderr}`);
    }
  });
}

出现此错误,

Error executing the adb file: Error: Command failed: cd ./tools/darwin/ && ./adb

此外,这段代码运行得很好,

const { exec } = require("child_process");

let commandOne = "ls -l"; // display all files in current directory with  (-l) long format
let commandTwo = "whoami"; // print the current user
let commandThree = "pwd"; //print the name of current directory

exec(`${commandOne} && ${commandTwo} && ${commandThree}`, (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`Output: ${stdout}`);
});
node.js shell command child-process
1个回答
-1
投票

cd ./tools/darwin/ && ./adb
是两个不同的命令,每个命令都会从您所在的位置执行。

const CHANGE_DIRECTORY_COMMAND = "cd ./tools/darwin/" const EXECUTE_ADB_COMMAND = "./adb" // exec(`${CHANGE_DIRECTORY_COMMAND} && ${EXECUTE_ADB_COMMAND}`, (error, stdout, stderr) => { // }); exec(EXECUTE_ADB_COMMAND, { cwd: CHANGE_DIRECTORY_COMMAND}, (error, stdout, stderr) => { });
    
© www.soinside.com 2019 - 2024. All rights reserved.