I've read a number of questions and answers on here regarding chokidar, however I'm still stumped... so would really appreciate anyone that can debug my specific snippet.

我在这里读了很多关于chokidar的问题和答案,但是我还是被难住了。因此,非常感谢能够调试我的特定代码片段的任何人。

I'm running a basic Express node app at localhost:3000.

我在localhost:3000运行一个基本的Express节点应用。

Entry point is app.js:

入口点是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;

and within ./routes/game.js:

和内。/线路/ 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;

Updating game.js (e.g., change "test-4" to "test-5") has no effect to the app without restarting the server. I had presumed that chokidar would allow me to update game.js and have the changes reflect on next page load?

更新游戏。js(例如,将“test-4”改为“test-5”)在不重启服务器的情况下对应用没有影响。我原以为chokidar会允许我更新游戏。js和更改是否反映了下一页的负载?

For reference the game.njk template looks like this:

供参考。njk模板如下:

{% extends "app.njk" %}

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

If I update the template, it updates instantly (as per nunjucks watch: true statement) but no luck on the also var updating.

如果我更新模板,它会立即更新(根据nunjucks watch: true语句),但是在var更新上没有什么好运气。

Appreciate any assistance.

感谢任何帮助。

1 个解决方案

#1


2

While you're clearing the cache, you're not renewing the game route. The cache flushing will work for newly required modules, but won't have any effect for already required ones. So you need to require again the game route after clearing the cache.

当你清理缓存时,你没有更新游戏路径。缓存刷新将为新需要的模块工作,但是对已经需要的模块没有任何影响。因此,在清除缓存之后,您需要再次要求游戏路径。

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");
            }
        });

And then change:

然后改变:

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

To:

:

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

In any case I would recommend using nodemon

无论如何,我建议使用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.

Nodemon是一个实用程序,它可以监视源中的任何更改并自动重启服务器。完美的发展。使用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:

只需使用nodemon而不是node来运行代码,现在当您的代码更改时,您的进程将自动重新启动。安装,得到节点。然后从终端运行:

npm install -g nodemon

And then:

然后:

nodemon server.js

更多相关文章

  1. 如何在Node中创建可重用的函数而不编写样板代码
  2. arcgis api for js入门开发系列十 自定义Navigation控件样式风格
  3. 五十行javascript代码实现简单的双向数据绑定
  4. 在内容可编辑DIV中的选定文本周围包装bb代码
  5. 常用验证JS代码基础及实例
  6. 试着在我的javascript代码中理解“this”(一件事有效,另一件没有)
  7. 是否可以知道文件是否在用户的浏览器缓存中?
  8. 代码点火-如何从控制器返回Json响应
  9. 小弟初学网页(javascript),看不懂下面的代码。但又要完成任务 各位

随机推荐

  1. 如何使用try,catch在错误处理中打印消息
  2. javascript之DOM技术(二)
  3. 有没有办法在javascript控制台中将上下文
  4. 如何使用Require JS配置具有第三方js依赖
  5. JavaScript——数组(三)数组方法汇总
  6. 切换元素类并使用旧类在视图中添加新元素
  7. 阻止用户在表单字段中输入
  8. req.files.upload.length返回文件计数为
  9. js 学习之路9:运算符
  10. 如何添加文本描述以指向谷歌地图API