关于我如何在Node.js中实现文件的自动重载有什么想法吗?我厌倦了每次更改文件时重新启动服务器。 显然,Node.js的require()函数不会重新加载文件,如果他们已经被要求,所以我需要做这样的事情:

var sys     = require('sys'), 
    http    = require('http'),
    posix   = require('posix'),
    json    = require('./json');

var script_name = '/some/path/to/app.js';
this.app = require('./app').app;

process.watchFile(script_name, function(curr, prev){
    posix.cat(script_name).addCallback(function(content){
        process.compile( content, script_name );
    });
});

http.createServer(this.app).listen( 8080 );

在app.js文件中,我有:

var file = require('./file');
this.app = function(req, res) { 
    file.serveFile( req, res, 'file.js');  
}

但这也不能工作-我在process.compile()语句中得到一个错误,说'require'没有定义。Process.compile正在计算app.js,但没有关于node.js全局变量的线索。


当前回答

const cleanCache = (moduleId) => {
    const module = require.cache[moduleId];
    if (!module) {
        return;
    }
    // 1. clean parent
    if (module.parent) {
        module.parent.children.splice(module.parent.children.indexOf(module), 1);
    }
    // 2. clean self
    require.cache[moduleId] = null;
};

其他回答

你可以通过浏览器刷新来实现。您的节点应用程序自动重启,您的结果页面在浏览器也自动刷新。缺点是你必须把js片段生成的页面。下面是工作示例的回购。

const http = require('http');
const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html; charset=UTF-8');
    res.write('Simple refresh!');
    res.write(`<script src=${process.env.BROWSER_REFRESH_URL}></script>`);
    res.end();
})

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);

    if (process.send) {
        process.send({ event: 'online', url: `http://${hostname}:${port}/` })
    }

});

一个好的、最新的替代supervisor的方法是nodemon:

监视node.js应用程序中的任何更改并自动重新启动服务器-非常适合开发

在没有npx的Node版本下使用nodemon(不建议使用v8.1及以下版本):

$ npm install nodemon -g
$ nodemon app.js

或者对捆绑了npx的Node版本使用nodemon (v8.2+):

$ npm install nodemon
$ npx nodemon app.js

或者在package.json中作为一个npm脚本中的devDependency:

"scripts": {
  "start": "nodemon app.js"
},
"devDependencies": {
  "nodemon": "..."
}

加载器是我的解决方案快速加载一个目录,递归。

可以返回

{'path/to/file': 'fileContents…'} 或 {path: {to: {file: 'fileContents'}}}

它有回调函数,当文件被更改时将被调用。

它处理的情况是文件足够大,以至于watch在写入完成之前就被调用。

我已经在项目中使用它一年左右了,最近才添加了承诺。

帮我进行战斗测试!

https://github.com/danschumann/loaddir

如果有人仍然遇到这个问题,并希望仅使用标准模块来解决它,我做了一个简单的例子:

var process = require('process');
var cp = require('child_process');
var fs = require('fs');

var server = cp.fork('server.js');
console.log('Server started');

fs.watchFile('server.js', function (event, filename) {
    server.kill();
    console.log('Server stopped');
    server = cp.fork('server.js');
    console.log('Server started');
});

process.on('SIGINT', function () {
    server.kill();
    fs.unwatchFile('server.js');
    process.exit();
});

这个例子只针对一个文件(server.js),但是可以使用一个文件数组,一个for循环来获取所有文件名,或者通过监视目录来适应多个文件:

fs.watch('./', function (event, filename) { // sub directory changes are not seen
    console.log(`restart server`);
    server.kill();
    server = cp.fork('server.js');    
})

这段代码是为Node.js 0.8 API制作的,它不适合一些特定的需求,但可以在一些简单的应用程序中工作。

更新: 这个函数是在我的模块simple, GitHub repo中实现的

现在WebPack开发服务器使用热选项。 您可以在包中添加这样的脚本。json: "hot": "cross-env NODE_ENV=development webpack-dev-server——hot——inline——watch-poll",

文件中的每一个变化都会自动触发重新编译