关于我如何在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全局变量的线索。


当前回答

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

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中实现的

其他回答

你可以通过浏览器刷新来实现。您的节点应用程序自动重启,您的结果页面在浏览器也自动刷新。缺点是你必须把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}/` })
    }

});

最近(2009年)在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;
};

如果你说的是服务器端的NodeJS热加载,假设你希望在服务器上有一个Javascript文件,它有一个描述的快速路由,你希望这个Javascript文件热加载,而不是在文件更改时服务器重新启动,那么razzle可以做到这一点。

basic-server就是一个例子

https://github.com/jaredpalmer/razzle/tree/master/examples/basic-server

如果更改并保存了https://github.com/jaredpalmer/razzle/blob/master/examples/basic-server/src/server.js文件,则该文件将热重新加载,服务器不会重新启动。

这意味着您可以编写一个REST服务器,它可以使用这个razzle进行热重载。

您可以通过Node-Supervisor进行安装

npm install supervisor

参见http://github.com/isaacs/node-supervisor