简体   繁体   中英

Nodejs Express PM2

im running an express api on a vm with nodejs and using pm2. I have a function running on setInterval and running every 30 seconds, the function gets data from an external api and then im concatenating the fetched data from the interval to the previous fetched data. I am importing the previous data ( const data = require('data.json') ).. Then i am using fs.writeFileSync to update the json file.

Then in my express routes, i am importing the json data file and sending the json data as the response. The problem im having is when i call the express route to get the data, the data being sent isn't the updated json file and does not include the lastest data from all the intervals. When i restart the app with pm2, then it then will send the lastest data. Can anyone help? Thanks

You definitively not use require to load datas. Instead, use fs module to load data, like this:

const fs = require( 'fs' );
myDatas  = fs.readFileSync( __dirname + '/data.json', 'utf8' );

mandatory parameter utf8 help reading file with the good encoding, if needed.

The example assume that data.json is in the same directory than your script. Can replace __dirname by full path or add relative path with or without conserving __dirname

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM