【问题标题】:Executing commands in parallel - nodejs并行执行命令 - nodejs
【发布时间】:2019-10-10 13:02:36
【问题描述】:

我需要一一执行许多命令,例如:

for(let i = 0; i < 1250; i++) { 
  spawn('cp', [`${myparam[i]}`, `${anotherParam[i]}`])
}

当然我得到Error: spawn /bin/sh EAGAIN。 我觉得这不是一个好方法。我的 cmd 必须包含有关数组中项目的一些信息。 做到这一点的最佳方法是什么?谷歌对这种情况一无所知...

确切地说: 我需要使用 mustache 解析大约 200 个 html 文件。我是通过 CLI 完成的,例如:

spawn('mustache', ['template.json', '${input}.html', '${output}.html'])

【问题讨论】:

标签: javascript node.js exec child-process spawn


【解决方案1】:

您可以将 mustache API 与 graceful-fs 一起使用。

Mustache.render替换你的命令

const fs = require("graceful-fs");
const Mustache = require("mustache");

const viewFile = "./template.json";

const input = ["input.html"];
const output = ["output.html"];

fs.readFile(viewFile, "utf8", (err, viewJson) => {
    if (err) throw err;

    const view = JSON.parse(viewJson);

    for (let i = 0, len = input.length; i < len; i++) { 
        fs.readFile(input[i], "utf8", (readErr, template) => {
            if (readErr) throw readErr

            fs.writeFile(output[i], Mustache.render(template, view), writeErr => {
                if (writeErr) throw writeErr;
            });
        });
    }
});

【讨论】: