简体   繁体   English

在Node.JS中打开多个进程

[英]Opening multiple processes in Node.JS

There was a question, I have the code on Node.JS and I want to open several similar files at the same time (by loop), when I try to do this via execFile / spawn, the script runs, but nothing happens. 有一个问题,我在Node.JS上有代码,我想同时(通过循环)打开几个类似的文件,当我尝试通过execFile / spawn来执行此操作时,脚本运行了,但是没有任何反应。 When you open a loop, a single file through execFile / spawn, everything happens fine, when opening several files through a double-click in the explorer, it is also normal. 当您打开一个循环(通过execFile / spawn生成一个文件)时,一切正常,当通过双击资源管理器中的多个文件打开文件时,这也是正常的。

I attach the code: 我附上代码:

 const spawn = require('child_process').spawn; const fs = require('fs'); var files = fs.readdirSync('D:\\\\Downloads\\\\runBots\\\\'); var countFiles = 0; var BotsProcess = new Array(10); var startApplication = function(){ for (var i in files) countFiles++; console.log("Bots in directory: " + countFiles); for(var j in countFiles) { BotsProcess[i] = spawn('D:\\\\Downloads\\\\runBots\\\\' + files[j], {shell : true}); } } startApplication(); 

The problem is the for loop. 问题是for循环。 The variable countFiles is a number, not an iterable. 变量countFiles是一个数字,不是可重复的。 You probably want 你可能想要

for (var j in files) {
    ...
}

Also, I cannot help but point out: 另外,我不禁指出:

To get countFiles, you can simply use files.length. 要获取countFiles,您可以简单地使用files.length。

You could also use a for of loop instead which will assign the value to j instead of the index, like this: 您也可以使用for for循环,它将为j而不是索引分配值,如下所示:

for(var j of files) {
    BotsProcess[i] = spawn('D:\\Downloads\\runBots\\' + j, {shell : true});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM