7

So inside my nodejs server file I have the line:

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. 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. 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?

Wingblade
  • 9,585
  • 10
  • 35
  • 48

5 Answers5

20

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');
Sv443
  • 708
  • 1
  • 7
  • 27
Teemu Ikonen
  • 11,861
  • 4
  • 22
  • 35
  • Gives me the error path is not defined. What module is it in? – Wingblade Oct 28 '12 at 16:42
  • 1
    Found it, it's in the path module. `path=require("path");` – Wingblade Oct 28 '12 at 17:11
  • I would suggest using `require.resolve()` instead of `path.resolve()` as `require` has specific rules for path resolution. If it's a custom module and you already know both would resolve to the same path, as in this case, then I guess it doesn't really matter. But. In general. – Jared Brandt May 06 '22 at 19:50
6

This solved it for me:

let tools = require("./tools.js"); 
delete require.cache[require.resolve("./tools.js")];
tools = require("./tools.js");

Creds to this answer

milmal
  • 526
  • 1
  • 9
  • 15
2

If I understood you correctly, you're running into Node's module 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. See https://github.com/isaacs/node-supervisor for instance.

AKX
  • 152,115
  • 15
  • 115
  • 172
2

Have a look at supervisor. Supervisor can restart the application automatically upon file changes and is simple to setup.

npm install -g supervisor

supervisor app.js

Menztrual
  • 40,867
  • 12
  • 57
  • 70
2

Once node.js require()s a module, any subsequent call to require() fetches it from memory, the actual module file doesn't get loaded again. 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.

Victor Stanciu
  • 12,037
  • 3
  • 26
  • 34