Azurasky Azurasky - 6 months ago 51
Node.js Question

Node.js filtered LS - missing ) after argument list

I'm completing the learnyounode workshop, and not sure what is wrong with my code. I ran it through jslint, it says:

Expected ')' to match '(' from line 6 and instead saw '{'.

Line 6 is blank. Can someone please point me in the right direction so that I can learn what I did wrong, correct it, and move on to the next exercise? Thanks.

var fs = require('fs');
var path = require('path');
var file = process.argv[2];
var ext = process.argv[3];
var filtered = [];

fs.readdir(file, callback(error, list) {
if (error) console.error(error);
else {
for (i = 0; i < list.length; i++) {
if (path.extname(list[i]) === ext) {
filtered.push(list[i]);
if (i === list.length - 1) {
console.log(filtered);
}
}
}
}
});


The condensed instructions are to read through a list of files in a directory and log the ones that have file extensions matching the one provided by the command line to the console.

Answer

You need to use function keyword:

fs.readdir(file, function(error, list) {
    if (error) console.error(error);
    else {
        for (i = 0; i < list.length; i++) {
            if (path.extname(list[i]) === ext) {
                filtered.push(list[i]);
                if (i === list.length - 1) {
                    console.log(filtered);
                }
            }
        }
    }   
});