node-swapper v0.2.0
node-swapper
Simple utility for hot code swapping in node.js.
Description
node-swapper replaces standard require()
function for more intelligent caching.
When first used, the library start watching the file required (using fs.watch()
).
#!javascript
var swapper = require("swapper");
swapper.require("/workspace/myFile.js");
When the file changes on disk, node-swapper automatically delete it from the module cache.
Thus, each time a file is required, it always returns the last version.
#!javascript
var swapper = require("swapper");
var data1 = swapper.require("/workspace/myFile.js");
// ... change contents of myFile.js
var data2 = swapper.require("/workspace/myFile.js");
// data1 != data2
How to use it ?
Use node-swapper require()
instead of node built-in and require modules only when you need to use it instead of requiring them once at start.
BAD way
#!javascript
var swapper = require("swapper");
var data = swapper.require("/workspace/myFile.js");
var app = Express();
app.get("/", function(req, res) {
// No magic: data will never change
res.end(data);
});
app.listen(port);
GOOD way
#!javascript
var swapper = require("swapper");
var app = Express();
app.get("/", function(req, res) {
// data may be updated at each HTTP request
var data = swapper.require("/workspace/myFile.js");
res.end(data);
});
app.listen(port);
Watch Mode
By default, node-swapper will use fs.watch()
backend to check when a file is updated.
However, it does not work for all file systems and especially not for files hosted on the network (Node.js documentation).
Thus, node-swapper can also use a more robust (but less efficient) approach: polling. This mode uses fs.unwatchFile()
backend and regularly check files stats.
It is possible to change mode by calling the watchMode()
function:
#!javascript
var swapper = require("swapper");
swapper.watchMode("STANDARD"); // Default efficient mode using fs.watch()
swapper.watchMode("POLLING"); // Polling mode using fs.watchFile()
You can select polling interval, but keep this value above one second at least (and higher if you require a lot of files):
#!javascript
swapper.interval = 3000; // polling interval in milliseconds
Note that polling mode is quite slower to detect changes (about 1 second), less reliable and more stressfull for your file system.
Limitations
Due to file system limitation, node-swapper may take some time (usually arround 100 milliseconds) to notice file change.
For now, node-swapper can only require absolute path.
If you don't know how to transform your relative path, try this:
#!javascript
var relativePath = "./myFile";
require(__dirname+"/"+relativePath);
Install
Quite straight forward:
npm install node-swapper
Running tests
Not that much complex either:
npm test
Help ?
This is the first time I publish a module. So feel free to point out errors and/or suggest modifications at hiryus01@gmail.com.
Pull requests welcome.