需要 node/express 个模块未使用 chokidar 更新?

required node/express modules not updating with chokidar?

我在这里阅读了许多关于 chokidar 的问题和答案,但我仍然感到困惑...所以非常感谢任何可以调试我的特定代码段的人。

我是 运行 localhost:3000 的基本 Express 节点应用程序。

入口点是app.js:

const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const clearRequire = require('clear-require');

const production = process.env.NODE_ENV === 'production';

const app = express();

// config nunjucks
const nunjucks = require('nunjucks');
nunjucks.configure('views', {
    autoescape: true,
    watch: true,
    nocache: true,
    express: app
});

// Routes for Express into modules
var index = require('./routes/index');
var game  = require('./routes/game');

if (!production) {
    const chokidar = require('chokidar');
    const watcher = chokidar.watch('./routes');

    watcher
        .on('ready', () => console.log('Scan complete. Ready for changes.'))
        .on('change', path => {
            var clearPath = "./" + path.split(".")[0];
            clearRequire(clearPath);
        });
}

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'njk');

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use('/', index);
app.use('/game', game);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error', { test: 'test'});
  next();
});

module.exports = app;

并在 ./routes/game.js:

var express = require('express');
var router = express.Router();

/* GET game page. */
router.get('/', function(req, res) {
  res.render('game', { title: 'Game', also: 'test-4' });
});

module.exports = router;

更新 game.js(例如,将 "test-4" 更改为 "test-5")在不重新启动服务器的情况下对应用程序没有影响。我以为 chokidar 会允许我更新 game.js 并让更改反映在下一页加载时?

作为参考,game.njk 模板如下所示:

{% extends "app.njk" %}

{% block pageContent %}
    <div id="pageContent" class="container">
        This. is. game. {{ also }}
    </div><!-- /#pageContent .container -->
{% endblock pageContent %}

如果我更新模板,它会立即更新(根据 nunjucks watch: true 声明)但 var 更新也没有运气。

感谢任何帮助。

当您清除缓存时,您并没有更新 game 路由。缓存刷新将对新需要的模块起作用,但对已经需要的模块没有任何影响。所以需要清缓存后重新require游戏路线

watcher
        .on('ready', () => console.log('Scan complete. Ready for changes.'))
        .on('change', path => {
            var clearPath = "./" + path.split(".")[0];
            clearRequire(clearPath);

            //Move this code elsewhere or not...
            if(path == "routes/game.js"){
               //renew game route
               game = require("./routes/game");
            }
        });

然后更改:

app.use('/game', game); //Changing game won't have any effect

收件人:

app.use('/game', function(req, res, next){
    game(req, res, next); //This game will have the renewed route
});

无论如何我会推荐使用nodemon

Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development. Install it using npm.

Just use nodemon instead of node to run your code, and now your process will automatically restart when your code changes. To install, get node.js, then from your terminal run:

npm install -g nodemon

然后:

nodemon server.js