Javascript 如何在 Node.js 中自动重新加载文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1972242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:10:50  来源:igfitidea点击:

How to auto-reload files in Node.js?

javascriptnode.js

提问by disc0dancer

Any ideas on how I could implement an auto-reload of files in Node.js? I'm tired of restarting the server every time I change a file. Apparently Node.js' require()function does not reload files if they already have been required, so I need to do something like this:

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

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

And in the app.jsfile I have:

app.js文件中,我有:

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

But this also isn't working - I get an error in the process.compile()statement saying that 'require' is not defined. process.compileis evaling the app.js, but has no clue about the node.js globals.

但这也不起作用 - 我在process.compile()声明中收到一条错误消息,指出未定义“require”。process.compile正在评估app.js,但对 node.js 全局变量一无所知。

回答by Marius Butuc

A good, up to date alternative to supervisoris nodemon:

一个好的、最新的替代方案supervisornodemon

Monitor for any changes in your node.js application and automatically restart the server - perfect for development

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

To use nodemon:

使用nodemon

$ npm install nodemon -g
$ nodemon app.js

回答by Anup Bishnoi

node-supervisor is awesome

节点主管很棒

usage to restart on save:

保存时重新启动的用法:

npm install supervisor -g
supervisor app.js

by isaacs - http://github.com/isaacs/node-supervisor

通过isaacs - http://github.com/isaacs/node-supervisor

回答by Inshua

i found a simple way:

我找到了一个简单的方法:

delete require.cache['/home/shimin/test2.js']

回答by micnic

If somebody still comes to this question and wants to solve it using only the standard modules I made a simple example:

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

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

This example is only for one file (server.js), but can be adapted to multiple files using an array of files, a for loop to get all file names, or by watching a directory:

此示例仅适用于一个文件 (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');    
})

This code was made for Node.js 0.8 API, it is not adapted for some specific needs but will work in some simple apps.

此代码是为 Node.js 0.8 API 编写的,它不适用于某些特定需求,但可以在一些简单的应用程序中使用。

UPDATE: This functional is implemented in my module simpleR, GitHub repo

更新:这个功能是在我的模块simpleR 中实现的GitHub repo

回答by JnBrymn

nodemoncame up first in a google search, and it seems to do the trick:

nodemon首先出现在谷歌搜索中,它似乎可以解决问题:

npm install nodemon -g
cd whatever_dir_holds_my_app
nodemon app.js

回答by Richard Metzler

There is Node-Supervisor that you can install by

您可以安装 Node-Supervisor

npm install supervisor

see http://github.com/isaacs/node-supervisor

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

回答by nalply

Edit:My answer is obsolete. Node.js is a very fast changing technology.

编辑:我的答案已过时。Node.js 是一种变化非常快的技术。

I also wondered about reloadingmodules. I modified node.js and have published the source at Github at nalply/node. The only difference is the function require. It has an optional second argument reload.

我也想知道重新加载模块。我修改了 node.js 并在 Github 的nalply/node 上发布了源代码。唯一的区别是功能require。它有一个可选的第二个参数reload

require(url, reload)

To reload app.jsin current directory use

app.js在当前目录中重新加载,请使用

app = require("./app", true);

Write something like this, and you have auto-reload:

写这样的东西,你有自动重新加载:

process.watchFile(script_name, function(curr, prev) {
    module = reload(script_name, true);
});

The only problem I see is the variable module, but I am working at it now.

我看到的唯一问题是变量module,但我现在正在处理它。

回答by Ninh Pham

nodemonis a great one. I just add more parameters for debugging and watching options.

nodemon是一个伟大的。我只是为调试和观看选项添加了更多参数。

package.json

包.json

  "scripts": {
    "dev": "cross-env NODE_ENV=development nodemon --watch server --inspect ./server/server.js"
  }

The command: nodemon --watch server --inspect ./server/server.js

命令: nodemon --watch server --inspect ./server/server.js

Whereas:

然而:

--watch serverRestart the app when changing .js, .mjs, .coffee, .litcoffee, and .jsonfiles in the serverfolder (included subfolders).

--watch server重新启动应用程序时更改.js.mjs.coffee.litcoffee,并.json在文件中的server文件夹(包括子文件夹)。

--inspectEnable remote debug.

--inspect启用远程调试。

./server/server.jsThe entry point.

./server/server.js入口点。

Then add the following config to launch.json(VS Code) and start debugging anytime.

然后将以下配置添加到launch.json(VS Code)并随时开始调试。

{
    "type": "node",
    "request": "attach",
    "name": "Attach",
    "protocol": "inspector",
    "port": 9229
}

Note that it's better to install nodemonas dev dependency of project. So your team members don't need to install it or remember the command arguments, they just npm run devand start hacking.

请注意,最好安装nodemon为项目的开发依赖项。所以你的团队成员不需要安装它或记住命令参数,他们只是npm run dev开始黑客攻击。

See more on nodemondocs: https://github.com/remy/nodemon#monitoring-multiple-directories

查看更多关于nodemon文档:https: //github.com/remy/nodemon#monitoring-multiple-directories

回答by Xavi

There was a recent threadabout this subject on the node.js mailing list. The short answer is no, it's currently not possible auto-reload required files, but several people have developed patches that add this feature.

有一个最近的线程关于Node.js的邮件列表,在这个问题上。简短的回答是否定的,目前不可能自动重新加载所需的文件,但有几个人已经开发了添加此功能的补丁。

回答by l3o

node-dev works great. npm install node-dev

node-dev 很好用。新产品经理install node-dev

It even gives a desktop notification when the server is reloaded and will give success or errors on the message.

它甚至会在服务器重新加载时发出桌面通知,并会在消息上显示成功或错误。

start your app on command line with:

在命令行上启动您的应用程序:

node-dev app.js

node-dev app.js