Extract ID3 Tags Node Script

On the off chance this is ever useful to anyone, here's a NodeJS script for extracting a bunch of ID3 tags to a CSV file. You'll need to install id3js (npm install id3js) in order to use it.

#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var id3 = require('id3js');

var dirs = [];

for (var i = 2; i < process.argv.length; i++) {
    dirs.push(process.argv[i]);
}

if (dirs.length == 0)
    dirs.push('.');

dirs.forEach(function(dir) {
    process.stderr.write("Scanning " + dir + "...\n");
    fs.readdir(dir, function(err, files) {
        if (err) {
            console.warn("Unable to read directory %s: %s", dir, err);
        } else {
            function grabTags(index) {
                while (index < files.length) {
                    var file = files[index];
                    index++;
                    if (file.length > 4 && file.substring(file.length-4).toLowerCase() == ".mp3") {
                        file = path.resolve(dir, file);
                        id3({ file: file, type: id3.OPEN_LOCAL}, function(err, tags) {
                            if (err) {
                                console.warn("Error reading %s: %j", file, err);
                            } else {
                                console.log("%s\t%s\t%s", tags["v2"]["track"], tags["v2"]["title"], tags["v2"]["artist"]);
                            }
                            grabTags(index);
                        });
                        return;
                    }
                }
            }
            grabTags(0);
        }
    });
});
Topics: