Home > front end >  Node.js exec to build Marp markdowns doesn't work
Node.js exec to build Marp markdowns doesn't work

Time:10-25

I wrote this simple node.js script to build Marp markdown and convert them to PDF. But it doesn't do anything and doesn't terminate. I added a console.log("test") at the end I see that node.js doesn't wait for all the command executions to finish but exec also doesn't run the Marp build command.

If I run the "cmd" string from the terminal it all works. I think something is wrong with the way I use exec

var glob = require("glob");
var cp = require("child_process");

glob("lab*/*.marp.md", {}, function (err, files) {
  files.forEach((file) => {
    var destination = file.replace(".md", "");
    var cmd = `marp ${file} --allow-local-files --pdf -o ${destination}.pdf`;
    var dir = cp.exec(cmd, (err, stdout, stderr) => {
      if (err) {
        console.log("node couldn't execute the command");
        return;
      }

      // the *entire* stdout and stderr (buffered)
      console.log(`stdout: ${stdout}`);
      console.log(`stderr: ${stderr}`);
    });

    dir.on("exit", function (code) {
      // exit code is code
      console.log(`finished building: ${file}`);
    });
  });
});

CodePudding user response:

you can try the execSync() function It'll solve the issue

var glob = require("glob");
var cp = require("child_process");

glob("lab*/*.marp.md", {}, function (err, files) {
  files.forEach((file) => {
    var destination = file.replace(".md", "");
    var cmd = `marp ${file} --allow-local-files --pdf -o ${destination}.pdf`;

    var dir = cp.execSync(cmd, (err, stdout, stderr) => {
      if (err) {
        console.log("node couldn't execute the command");
        return;
      }

      // the *entire* stdout and stderr (buffered)
      console.log(`stdout: ${stdout}`);
      console.log(`stderr: ${stderr}`);
    });

    dir.on("exit", function (code) {
      // exit code is code
      console.log(`finished building: ${file}`);
    });
  });
});
  • Related