我嘗試使用子行程執行命令,但無法使用 nodejs 通過絕對路徑執行,但是當我使用終端時,一切都很好。
這是為什么?
我的代碼就在這里:
const cp = require('child_process');
const commandExecutor = 'node-install/target/node/yarn/dist/bin/yarn.exe';
const symlinkFolder = 'node-install/target/node/target/symlink';
const workingDirectories = [];
Array.from(process.argv).forEach((value, index) => {
if (index >= 2) {
workingDirectories[index - 2] = value;
}
});
workingDirectories.forEach(function(workingDirectory) {
const argumentsUnlink = 'unlink @item@ --link-folder ' symlinkFolder ' --cwd ' workingDirectory;
const unlinkCommand = commandExecutor ' ' argumentsUnlink;
const execution = cp.exec(
unlinkCommand,
function (error, stdout, stderr) {
console.log(stdout);
console.log(error);
console.log(stderr);
});
execution.on('exit', function (code) {
let message = 'Child process exited with exit code ' code ' on route ' workingDirectory;
console.log(message);
});
});
命令的一個例子是:
node-install/target/node/yarn/dist/bin/yarn.exe unlink @item@ --link-folder node-install/target/node/target/symlink --cwd appointments/target/generated-sources/frontend/
但我得到的錯誤是:
'node-install' is not recognized as an internal or external command, operable program or batch file.
當我從終端執行命令時,一切都很好。
uj5u.com熱心網友回復:
可能的問題之一 - NodeJs 無法通過相對路徑定位檔案。您可以使用構造絕對路徑來解決此問題,如果 node-install 位于您的專案根目錄(不是最終串列)中,則很少有選項可以提供幫助:
__dirname, 回傳當前模塊的目錄,所以如果
node-install/../..
index.js
那么在index.js我們可以使用
const commandExecutor = `${__dirname}/node-install/target/node/yarn/dist/bin/yarn.exe`;
process.cwd(),它回傳行程根的完整路徑,所以如果你從檔案夾中啟動nodejsnode-install,那么你可以像這樣參考exe:
const commandExecutor = `${process.cwd()}/node-install/target/node/yarn/dist/bin/yarn.exe`;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/349260.html
標籤:javascript 节点.js 视窗 猛击 贝壳
