简体   繁体   English

用于构建 Marp 降价的 Node.js exec 不起作用

[英]Node.js exec to build Marp markdowns doesn't work

I wrote this simple node.js script to build Marp markdown and convert them to PDF.我编写了这个简单的 node.js 脚本来构建 Marp markdown 并将它们转换为 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.我在最后添加了一个console.log("test")我看到 node.js 不会等待所有命令执行完成,但exec也不会运行 Marp 构建命令。

If I run the "cmd" string from the terminal it all works.如果我从终端运行“cmd”字符串,则一切正常。 I think something is wrong with the way I use exec我认为我使用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}`);
    });
  });
});

you can try the execSync() function It'll solve the issue你可以试试 execSync() 函数它会解决这个问题

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}`);
    });
  });
});

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

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