[英]Arguments for Node child_process "spawn()"
使用 child_process (spawn) 打开一个新的 BASH 终端并执行每个文件中的命令。
我想将我要生成的所有 my.sh 文件添加到一个文件夹中以清理我的项目目录。
问题:我不知道如何更改脚本运行的目录,此时文档对我来说有点重。
简单的测试示例,使用我的前两个连接文件(每个 .sh 文件将位于项目文件夹中):
const { spawn } = require('node:child_process');
const bat = spawn('cmd.exe', ['/c', 'connect.sh']);
/*
<connect.sh> // 1st .sh file
#!/usr/bin/env bash //to make it bash
HTTP_PORT=3002 P2P_PORT=5002 PEERS=ws://localhost:5001 npm run dev
<connect1.sh> // 2nd .sh file
#!/usr/bin/env bash //to make it bash
HTTP_PORT=3003 P2P_PORT=5003 PEERS=ws://localhost:5002,ws://localhost:5001 npm run dev
*/
我有 9 个这样的文件可以连接多达 10 个对等点。 我想将它们放在一个文件夹中以简化我的项目结构。
这是我下面的实际 API 调用.... // 使用长度来确定要运行的文件
app.post("/peers/connect", async function (req, res) {
const peerInfo = await peers.info();
// no peers yet
if (typeof peerInfo === "string") {
let bat = spawn("cmd.exe", ["/c", "connect.sh"]);
res.json("A new terminal has opened! You are now connected!");
} else {
// peers exist
let length = peerInfo.peers;
// console.log(length);
let bat = spawn("cmd.exe", ["/c", `connect${length}.sh`]);
res.json("A new terminal has opened! You are now connected!");
}
});
我的文件结构在这里......你可以明白为什么我想要一个文件夹!
回顾:帮助我将所有这些文件放入一个文件夹 (shellScripts) 并让代码仍然有效:) 谢谢? (刚刚意识到我们可能必须在每个文件中的“npm run dev”之前 cd 回到项目文件夹?)
您正在使用 cmd.exe 实用程序来运行 .sh 文件,但这不起作用。 您必须在 windows 设备上安装 bash 解释器或安装 WSL。 (如有必要,将 bash.exe 添加到 windows 路径)然后将代码更改为:
const { spawn } = require('node:child_process');
const bat = spawn('bash.exe',['connect.sh']);
我希望这个答案有所帮助
对于运行多个文件:
const { spawn } = require('node:child_process');
const fs = require("node:fs")
const dir = "" // Replace this with the location of the directory containing connect shellscripts
let entrys = fs.readdirSync(dir)
entrys = entrys.filter(v=>v.startsWith("connect"))
for(let ent of entrys){
const bat = spawn('bash.exe',[ent]);
// your code here
}
我自己想出了答案。 感谢所有试图提供帮助的人:) 对于那些说我上面的代码不起作用的人,它工作得很好。
我提供了一张图片来澄清。 第一个是下面的代码产生的。 第二个是手动将其粘贴到 GIT BASH 中。
// test.js in project structure pic above
var exec = require('child_process').exec;
var path = require('path')
var parentDir = path.resolve(process.cwd(), 'shellScripts');
exec('my.sh', {cwd: parentDir}, function (error, stdout, stderr) {
// if you also want to change current process working directory:
process.chdir(parentDir);
});
这是在项目文件夹中打开一个 GIT BASH 并将命令粘贴到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.