我撰寫了這個簡單的 node.js 腳本來構建 Marp markdown 并將它們轉換為 PDF。但它什么也不做,也不會終止。我console.log("test")在最后添加了一個我看到 node.js 不會等待所有命令執行完成,但exec也不會運行 Marp 構建命令。
如果我從終端運行“cmd”字串,則一切正常。我認為我的使用方式有問題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}`);
});
});
});
uj5u.com熱心網友回復:
你可以試試 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}`);
});
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334955.html
標籤:javascript 节点.js 马尔普
上一篇:如何解決未捕獲的型別錯誤:嘗試使用JS和html顯示當前時間時,無法在列印時間設定null的屬性(設定“innerHTML”)
