inzkornel
inzkornel

Reputation: 33

Executing commands in parallel - nodejs

I need to execute many commands one by one something like:

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

And of course im getting Error: spawn /bin/sh EAGAIN. I feel that this is not good approach. My cmd must contain some info about item from array. What is the best approach to do this? Google tells nothing about situations like that...

To be exact: I need to parse about 200 html files using mustache. I did it via CLI like:

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

Upvotes: 0

Views: 223

Answers (1)

frobinsonj
frobinsonj

Reputation: 1167

You could use the mustache API along with graceful-fs.

Replace your command with 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;
            });
        });
    }
});

Upvotes: 0

Related Questions