0

I'm writing a method that uses async/await and promises to write some JSON to a file and then render a pug template. But for some reason the code that writes the JSON conflicts with the res.render() method resulting in the browser not being able to connect to the server.

The weird thing is that I don't get any errors in the console, and the JSON file is generated as expected — the page just won't render.

I'm using the fs-extra module to write to disk.

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...',
    });
}

I'm starting to think that there is something fundamental I'm not getting that conflicts with promises, writing to disk and/or express' res.render method. It's worth noting that res.send() works fine.

I've also tried a different NPM module to write the file (write-json-file). It gave me the exact same issue.

UPDATE: So I'm an idiot. The problem has nothing to do with Express og the JSON file. It has to do with the fact that I'm running nodemon to automatically restart the server when files are changed. So as soon as the JSON file was saved the server would restart, stopping the process of rendering the page. Apologies to the awesome people trying to help me anyway. You still helped me get to the problem, so I really appreciate it!

Malibur
  • 1,695
  • 5
  • 22
  • 31
  • Does the `res.render()` work fine by itself if you comment out the writing of the JSON file? – jfriend00 Jan 17 '18 at 15:47
  • Is there any chance that `fse.writeJson()` might be changing the current directory causing your `res.render()` to not be able to find the filename? I'd suggest you add a callback to `res.render()` and see if it's returning an error code. – jfriend00 Jan 17 '18 at 15:50
  • the res.render works fine if i comment out that line yes. – Malibur Jan 17 '18 at 16:10
  • Not sure what you mean by adding a callback to res.render. could you explain how I do that. You may be right about the directory thing. Not sure how to test it or work around it though – Malibur Jan 17 '18 at 16:11
  • @jfriend00 Ah, just got what you mean. Unfortunately, it doesn't give me an error when adding a callback to res.render(). – Malibur Jan 17 '18 at 16:31

1 Answers1

2

Here's the actual problem:

The OP is running nodemon to restart the server whenever it see filechanges, and this is what stops the code from running, because as soon as the json file is generated the server restarts.


Efforts to troubleshoot:

It's going to take some trouble shooting to figure this out and since I need to show you code, I will put it in an answer even though I don't yet know what is causing the problem. I'd suggest you fully instrument things with this code:

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");
     }
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • thank you so much for taking the time to write this out. The same thing happen, with this result in the console: – Malibur Jan 17 '18 at 16:54
  • the two cwd commands returns the same working directory ending with '/app' – Malibur Jan 17 '18 at 16:54
  • then "about to call res.render()' is printet as the last thing. – Malibur Jan 17 '18 at 16:55
  • "JSON updated" is also printet between the two cwd logs – Malibur Jan 17 '18 at 16:56
  • @MaltheMilthers - I added a couple more `console.log()` statements. Please rerun with that and capture the whole console logs. Are you saying that `"after calling res.render()"` does not show in the logs? I need to see the entire console output. Can you put that in some online resource such as a jsFiddle or some other free place on the web and then drop a link here so I can see the exact text in the console? – jfriend00 Jan 17 '18 at 17:03
  • omg I just realised what was going on. I'm an idiot. I'm running nodemon to restart the server whenever it see filechanges, and this is what stops the code from running, because as soon as the json file is generated the server restarts. I'm so sorry for this goose-chase, but you actually helped me find out the issue. How to I best give you points for your effort? – Malibur Jan 17 '18 at 17:07
  • @MaltheMilthers - I added that to the start of my answer. You can click the checkmark to the left of this answer to indicate this was the solution. – jfriend00 Jan 17 '18 at 17:10