Reputation: 421
I am new to nodejs and did some test on my nodejs app. The code is basically like this.
import express from 'express';
import jsonfile from "jsonfile";
const app = express();
const PORT = process.env.PORT || 3002;
let global=0;
app.use(express.static(`${__dirname}/assets`));
app.use((req, res, next) => {
//write file
const file = '/path/data.json';
var obj = {
name:'cd'
};
jsonfile.writeFile(file,obj,{spaces: 2}, (err)=>{
console.error(err);
})
next();
})
app.get('/test', (req, res, next) => {
global++
res.send(''+global);
})
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}!`);
});
I built it on localhost, and input http://localhost:3002/test into the browser. The app will send the global counter to the browser, but if I refresh the page, I found my nodejs app restart and the counter doesn't change. If I comment out the jsonfile.writeFile part and do the same process like before, the nodejs app won't restart and the counter will increase every time I refresh the page. Why is that?
Upvotes: 1
Views: 1452
Reputation: 15639
As you've commented the nodemon
forces the page reload (live reload) to enable you to see the changes instantly.
Use node <your_script_name.js>
or node <any_command_defined_in_scripts>
(whatever is applicable) instead of nodemon
if you don't want auto-refresh every time when you refresh the page.
Hope this helps!
Upvotes: 2