简体   繁体   中英

Editing NodeJS file while it is executing

This should be a trivial question. Say that I have my pretty file, foo.js . I run it with node foo.js . It runs and runs and runs. While it is still running, I open my favorite text editor and edit foo.js , adding a whole lot of errors to the code.

Can I be sure that this won't affect the current execution of foo.js ? Am I right when I assume that the file will be read at the beginning of the execution, and then there will be no need to read it again since it will be kept in memory? Or could an edit to the file cause something when it is already executing?

The node.js code model for the initial file you specify on the command line such as node foo.js is that, at startup, foo.js is read from disk, parsed into Javascript byte code and then executed. Any functions or variables you define in that file are kept in memory from then on. There is no circumstance where node.js will, entirely on its own, reread foo.js .

Some potential places where it could get reread are:

  1. If you have some specific code that refers to foo.js on disk such as a require() statement or some code that actually reads it from disk.

  2. If you use any auto-restart tools such as forever . In that case, if your process crashes and forever restarts it, it would obviously read a fresh copy of foo.js during the restart.

  3. If you fork, spawn or exec your own process. Note this could happen in some forms of dynamic clustering or some types of code that start up a new process only in some circumstances.

When executing a file with Node.JS, it is read only once. If you edit the file during the execution, it won't affect the execution. You can safely edit it without worrying about errors.

Of course it's different if you are loading some modules dynamically, for example:

setTimeout(function() {
  var myModule = require("./myModule.js");
}, 10000);

If you edit myModule.js before it has been loaded, it would be loaded with the changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM