process.on()不是一个函数。

3
我对Node.js还比较新,不太确定完全理解这个错误的含义是什么:

(原文)

process.on('uncaughtException', err => {

   ^

TypeError: process.on is not a function

我读到过,不应该导入process,因为它会自动注入。我的代码是这样的:
var settings;

var jsonfile = require("jsonfile");
var file = "server/settings.json";

try {
    var obj = jsonfile.readFileSync(file);
    settings = obj;

} catch (err) {
    var msg = err + ". Exiting";
    console.error(msg);
    throw new Error("Fatal");
}

// some other functions

process.on('uncaughtException', function (err) {
    console.error((new Date).toUTCString() + ' uncaughtException:', err.message)
    console.error(err.stack)
    process.exit(1)
  })

module.exports.login = login;
module.exports.logout = logout;

我的意图是,如果我无法读取设置文件,则退出。这是按设计进行的。我知道其他方法可能更好,但我的问题是为什么会出现上述错误?我正在运行 Node.js 8.12.0,在 Windows 7 64 位上运行。
2个回答

4
如果你想添加这个功能,你可以在你的app.js或者server.js文件的结尾处使用它。它会全局捕获任何未捕获的错误并将其记录下来。
app.listen(port, () => console.log(`app listening on port ${port}!`));

process.on('uncaughtException', function (error) {
    console.log(error);
}); 

所以,导出并不是必要的...



0

你应该将 process.on() 函数放在 try catch 之前,否则你的 uncaughtException 事件将不会生效。

var settings;

var jsonfile = require("jsonfile");
var file = "server/settings.json";

process.on('uncaughtException', function (err) {
    console.error((new Date).toUTCString() + ' uncaughtException:', err.message)
    console.error(err.stack)
    process.exit(1)
})

try {
    var obj = jsonfile.readFileSync(file);
    settings = obj;

} catch (err) {
    var msg = err + ". Exiting";
    console.error(msg);
    throw new Error("Fatal");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接