Thursday, March 20, 2014

Nodejs Watching a file + Spawning new processes to list file information

Hi guys - Trying to get my hands dirty with Node.js and its pretty cool.

Its so easy to do stuff. Here is a small code snippet which demonstrate watching a file and spawning a child process to list the file info.

var fs = require('fs');
var spawnProcess = require('child_process').spawn;
var filename = 'some/file'
fs.watch(filename, function() {
var list = spawnProcess('ls', ['-lh', filename]);
var info = '';
// listener get invoked every time a chunk of data is available. Data is read in chunks
list.stdout.on('data', function(chunk) {
output += chunk.toString();
});
// When child process exit, it emits the close event
list.on('close', function() {
var parts = output.split(/\s+/);
console.dir([parts[0], parts[4], parts[8]]);
});
});


Thanks


No comments:

Post a Comment