Search code examples
javascriptnode.jsgoogle-app-enginefs

fs.writeFile works on localhost but not production server


I have a basic web app setup that has a file structure that resembles this:

WEB APP
 - data
   -year.txt

 - cron
   -write.js

One parent directory with two folders each containing a single file. The write.js file generates a bunch of data on the backend, JSON.stringifies that data and writes the string to the year.txt file located in the other folder. This is what it looks like in the write.js file:

try {
   fs.writeFile(__dirname + '/../data/year.txt', JSON.stringify(organizedData), () => {
      console.log('SUCCESS');
      res.status(200);
      res.send(null);
    });
} catch (e) {
      res.status(500);
      console.log(e);
      res.send(null);
}

All of this works fine on my LOCAL server, the write.js file updates the year.txt with the correct data. I'm just struggling to figure out why this wont work on my production server, which is hosted on Google Cloud App Engine. The part that really confuses me is when I check the logs on this production server I get the "SUCCESS" message, which means the fs.writeFile function isn't throwing any errors. I check the year.txt file url path, and nothing is added. I can't seem to figure this out, does it maybe have something to do with the file path in the writeFile function?


Solution

  • fs.writeFile() passes its errors to the callback as the first argument err (which you are not paying any attention to). So, the first thing for you to do is to log the actual error fs.writeFile() is getting. But, I would "guess" that it's a file permission error for the directory you're trying to write to in your hosting configuration.

    fs.writeFile() does not communicate errors by throwing an exception. So, you need to catch errors like this:

       fs.writeFile(__dirname + '/../data/year.txt', JSON.stringify(organizedData), (err) => {
          if (err) {
              console.log(err);
              res.sendStatus(500);
          } else {
              console.log('SUCCESS');
              res.sendStatus(200);
       });
    

    does it maybe have something to do with the file path in the writeFile function

    Yes, probably. But logging the actual error will give you more info. You can also read some doc on your hosting configuration to find out where exactly you are allowed to write to from your server process.

    Here's a reference from the Google Cloud app engine docs on writing data to files. It suggests you either write to the temp directory or you write to Google Cloud storage.