Node is becoming my general purpose scripting tool

Back to Listing

Node is becoming my general purpose scripting tool


24 Apr, 2013


For the last week or so we have had an issue with our continuous build hanging while executing a specific test suit. It has been causing a lot of heartache on the team and making our deployment process incredibly unreliable and painful.

This particular test suite does not change very often as it holds all of our integration tests which we try to avoid adding things to because of the time cost when running them. I wanted to get a list of files along with their last change date, but a quick google search didn't turn up anything easy.

I did find a StackOverflow article that showed how to get the information for a specific file. So, I fired up Sublime Text 2 and hacked out a little node script to traverse a directory structure and build up a list of files, then execute the git command on each writing out the result to the console.

I executed my script and piped it out to a text file and had my data.

var fs = require('fs'),  
    exec = require('child_process').exec;

var ROOT_PATH = 'Tests.Integration';

var endsWith =function(str, suffix) {  
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

var exclude = function(dir){  
    return endsWith(dir, 'bin') || endsWith(dir, 'obj');
};

var walk = function(dir, done) {  
  var results = [];
  fs.readdir(dir, function(err, list) {
    if (err) return done(err);
    var pending = list.length;
    if (!pending) return done(null, results);
    list.forEach(function(file) {
      file = dir + '/' + file;
      fs.stat(file, function(err, stat) {
        if (stat && stat.isDirectory()) {
          if(exclude(file)) 
            return --pending;
          walk(file, function(err, res) {
              results = results.concat(res);
            if (!--pending) done(null, results);
          });
        } else {
          results.push(file);
          if (!--pending) done(null, results);
        }
      });
    });
  });
};

walk(ROOT_PATH, function(err, results){  
    results.forEach(function(file){
        var command = "git log -1 --format=%ci " + file;
        exec(command, function(error, stdout, stderr){
            console.log(stdout.trim() + '\t' + file);
        });
    });
});

This is obviously spastic cut and paste code, but it got the job done. I am sure there are untold millions of possible better ways to have accomplished this with bash or powershell or (insert your favorite thing here), but node is what I reached for becuase I feel the most comfortable with it.

Share this story

Bobby Johnson

About Author

I am a passionate engineer with an interest in shipping quality software, building strong collaborative teams and continuous improvement of my skills, team and the product.

comments powered by Disqus
Back to top