node express:将文件写入磁盘后 res.render() 出现问题



我正在编写一个使用 async/await 的方法,并承诺将一些 JSON 写入文件,然后渲染一个 pug 模板。但由于某种原因,编写 JSON 的代码与 res.render() 方法冲突,导致浏览器无法连接到服务器。

奇怪的是,我在控制台中没有收到任何错误,并且 JSON 文件按预期生成——页面只是不会呈现。

我正在使用 fs-extra 模块写入磁盘。

const fse = require('fs-extra');
exports.testJSON = async (req, res) => {
await fse.writeJson('./data/foo.json', {Key: '123'})
.then(function(){
console.log('JSON updated.')
})
.catch(function(err){
console.error(err);
});
res.render('frontpage', {
title: 'JSON Updated...',
});
}

我开始认为有一些基本的东西我没有得到与承诺,写入磁盘和/或表达的res.render方法相冲突。值得注意的是,res.send() 工作正常。

我还尝试了不同的 NPM 模块来写入文件(write-json-file)。它给了我完全相同的问题。

更新: 所以我是个白痴。该问题与Express og the JSON 文件无关。这与我正在运行nodemon以在文件更改时自动重新启动服务器的事实有关。因此,一旦保存了 JSON 文件,服务器就会重新启动,停止呈现页面的过程。向试图帮助我的真人道歉。你仍然帮助我解决了问题,所以我真的很感激!

这是实际问题:

OP 正在运行 nodemon 以在看到文件更改时重新启动服务器,这就是阻止代码运行的原因,因为一旦生成 json 文件,服务器就会重新启动。


故障排除工作:

要解决这个问题需要一些麻烦,因为我需要向您展示代码,即使我还不知道导致问题的原因,我也会把它放在答案中。 我建议你用这段代码完全检测东西:

const fse = require('fs-extra');
exports.testJSON = async (req, res) => {
try {    
console.log(`1:cwd - ${process.cwd()}`);
await fse.writeJson('./data/foo.json', {Key: '123'})
.then(function(){
console.log('JSON updated.')
}).catch(function(err){
console.error(err);
});
console.log(`2:cwd - ${process.cwd()}`);
console.log("about to call res.render()");    
res.render('frontpage', {title: 'JSON Updated...',}, (err, html) => {
if (err) {
console.log(`res.render() error: ${err}`);
res.status(500).send("render error");
} else {
console.log("res.render() success 1");
console.log(`render length: ${html.length}`);
console.log(`render string (first part): ${html.slice(0, 20}`);
res.send(html);
console.log("res.render() success 2");
}
});
console.log("after calling res.render()");
} catch(e) {
console.log(`exception caught: ${e}`);
res.status(500).send("unknown exception");
}
}

最新更新