[英]Nodejs require returns same old file when requiring a second time after the file changed
So inside my nodejs server file I have the line:所以在我的 nodejs 服务器文件中,我有一行:
tools=require("./tools.js");
The tools file contains functions and thelike that I change alot, so I figured instead of restarting the server everytime I change something, I could simply add some way for me to re-require the tools.js, and so I did.工具文件包含我经常更改的函数等,所以我想不是每次更改时都重新启动服务器,我可以简单地添加一些方法让我重新需要 tools.js,所以我做到了。 However now the problem is, when I start the program, change the tools.js and make it re-require it, it requires it again as if it was still in the state it was when it was first required.
但是现在的问题是,当我启动程序时,更改 tools.js 并使其重新需要它,它再次需要它,就好像它仍然处于第一次需要时的状态一样。 What?
什么?
Edit: I don't want to restart the app upon a file change, since that would be the same as restarting the server, which is what I want to prevent!编辑:我不想在文件更改时重新启动应用程序,因为这与重新启动服务器相同,这是我想要防止的! So I need something that let's me re-require it, ignoring module caching or whatever.
所以我需要一些让我重新需要它的东西,忽略模块缓存或其他什么。
Any ideas what could help me here?有什么想法可以帮助我吗?
If you don't want to restart the app do this every time you require it.如果您不想重新启动应用程序,请在每次需要时执行此操作。
var path = require('path');
var filename = path.resolve('./tools.js');
delete require.cache[filename];
var tools = require('./tools');
If I understood you correctly, you're running into Node's module caching.如果我理解正确,您就会遇到 Node 的模块缓存。 http://nodejs.org/docs/latest/api/modules.html#modules_caching
http://nodejs.org/docs/latest/api/modules.html#modules_caching
You might want to look into a proper reloader for Node instead, if that's an option.如果这是一个选项,您可能想要为 Node 寻找合适的重新加载器。 See https://github.com/isaacs/node-supervisor for instance.
例如,请参见https://github.com/isaacs/node-supervisor 。
Have a look at supervisor.看看主管。 Supervisor can restart the application automatically upon file changes and is simple to setup.
Supervisor 可以在文件更改时自动重新启动应用程序,并且设置简单。
npm install -g supervisor
supervisor app.js
Once node.js require()sa module, any subsequent call to require() fetches it from memory, the actual module file doesn't get loaded again.一旦 node.js require()sa 模块,任何对 require() 的后续调用从内存中获取它,实际的模块文件就不会再次加载。 What you need to do is use a tool like nodemon (https://github.com/remy/nodemon ), which automatically restarts your app when files are changed.
您需要做的是使用像 nodemon (https://github.com/remy/nodemon ) 这样的工具,它会在文件更改时自动重新启动您的应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.