Tag Archives: cli

NodeJS – FileSystem + process.argv

Today’s (actually yesterday’s) example of Node is focused on FileSystem. It is a really simple file reader/writer example that explores a couple of concepts: read a file contents, write new contents to it and monitor file changes.

A little plus to the example was to add a command line argument in order to disable self-updating of the log file.

A note: My original plan was to explore the API in order to make these examples as much OS independent as possible but in this case, the file watch does not work on Windows hence, I’ll add a note on future examples to let you know if the code is testable on Windows boxes or not.

A screenshot of the code running with self-updating enabled (default)

A screenshot of the code running with self-updating disabled (“–no-update”). Notice the updates in the active console to test.log file and the console in background is echoing the changes.

And the code

var fs = require("fs");
var filename = __dirname + "/test.log";
 
var FileSystem = {
 initialize: function() {
  fs.readFile(filename, "utf8", function(err, data) {
   if (data == undefined) {
    fs.writeFile(filename, "0", "utf8");
   }
  });
 
  fs.watchFile(filename, FileSystem.watch);
 
  if (process.argv.length == 2 || (process.argv.length > 2 && process.argv.join(" ").indexOf("--no-update") < 0)) {
   setInterval(FileSystem.update, 1000);
  }
 
 },
 
 update: function() {
  var val = Math.round(Math.random() * 100);
  fs.writeFile(filename, val.toString(), "utf8");
 },
 
 watch: function(curr, prev) {
  if (curr.mtime <= prev.mtime) {
   return;
  }
 
  fs.readFile(filename, "utf8", function(err, data) {
   console.log("The new content of %s is: %s", filename, data);
  });
 }
};
 
FileSystem.initialize();