鍍金池/ 問(wèn)答/HTML/ nodejs異常捕獲的問(wèn)題

nodejs異常捕獲的問(wèn)題

請(qǐng)問(wèn)nodejs能不能捕獲require模塊時(shí)的異常,比如該文件不存在。

我試過(guò)try...catch發(fā)現(xiàn)不行

回答
編輯回答
乖乖噠

啟動(dòng)階段已經(jīng)跪了吧

2018年8月11日 03:26
編輯回答
乞許

讀取文件用fs啊,require是引入代碼模塊的,代碼模塊存在不存在,你自己心里沒(méi)點(diǎn)x數(shù)嗎

其實(shí)你的需求是異步加載,es6的import()函數(shù)(注意:不是import關(guān)鍵字)可以做到:

import(`./section-modules/${someVariable}.js`)
  .then(module => {
    module.loadPageInto(main);
  })
  .catch(err => {
    main.textContent = err.message;
  });

引自阮一峰的ECMAScript 6 入門

不過(guò)nodejs不支持import()函數(shù),可以用require.async包實(shí)現(xiàn).

require.async地址

require("require.async")(require)
require.async("moment", function(moment) {
    console.log(moment().unix())
})

這要求所有的代碼都是異步的

2018年4月12日 22:34