gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:02:11 24 4
gpt4 key购买 nike

关于如何在 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 全局变量一无所知。

最佳答案

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

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

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

$ npm install nodemon -g
$ nodemon app.js

或者将 nodemon 与带有 npx 的 Node 版本一起使用(v8.2+):

$ npm install nodemon
$ npx nodemon app.js

或者在 package.json 中使用 npm 脚本作为 devDependency:

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

关于javascript - 如何在 Node.js 中自动重新加载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1972242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com