在节点应用程序中,是否可能需要一个脚本停止其父脚本的进一步执行?
假设a.js
需要b.js
。 b.js
是否可以停止对a.js
的处理?
a.js
require('b.js')
// some other code that I might not want to execute
b.js
if (/* we do want `a.js` to continue */) {
return
} else {
// somehow stop `a.js` from being further processed
}
理想情况下,该解决方案不会涉及生成子进程:)对此的任何见解将不胜感激!谢谢!
答案 0 :(得分:1)
导出抛出的函数:
module.exports = function() {
// In case you want to end the parents execution:
throw new Error("I just want to be mean");
};
然后将其用作:
require("b.js")();
console.log("this will never happen");
答案 1 :(得分:0)
答案比我最初意识到的要简单:
a.js
const b = require('b.js')
// calling 'b' returns true if should terminate `a.js`
if (b()) {
return
}
// the rest of script `a.js`
b.js
module.exports = () => {
// run whatever,
// return boolean (whether to further-execute `a.js`)
}