为什么每次刷新客户端页面时nodej都会重新启动

时间:2017-10-20 06:45:42

标签: node.js

我是nodejs的新手,并在我的nodejs app上做了一些测试。代码基本上就是这样。

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}!`);
});

我在localhost上构建它,并在浏览器中输入http://localhost:3002/test。该应用程序将全局计数器发送到浏览器,但如果我刷新页面,我发现我的nodejs应用程序重新启动,计数器不会更改。如果我注释掉jsonfile.writeFile部分并像以前一样执行相同的过程,则nodejs应用程序将不会重新启动,并且每次刷新页面时计数器都会增加。那是为什么?

1 个答案:

答案 0 :(得分:1)

正如您评论nodemon强制页面重新加载(实时重新加载),以便您立即查看更改。

如果您不想在每次刷新页面时自动刷新,请使用node <your_script_name.js>node <any_command_defined_in_scripts>(适用的任何内容)而不是nodemon

希望这有帮助!

相关问题