首页 > 解决方案 > 并行执行命令 - nodejs

问题描述

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

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'])

标签: javascriptnode.jsexecchild-processspawn

解决方案


您可以将 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;
            });
        });
    }
});


推荐阅读