0

我正在编写一个使用 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 JSON 文件无关。这与我正在运行 nodemon 以在文件更改时自动重新启动服务器这一事实有关。因此,一旦保存了 JSON 文件,服务器就会重新启动,从而停止呈现页面的过程。无论如何,向那些试图帮助我的很棒的人道歉。你仍然帮助我解决了这个问题,所以我真的很感激!

4

1 回答 1

2

这是实际的问题:

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");
     }
}
于 2018-01-17T16:45:53.010 回答