Node.JS (Make it Modular) error callback?

Hey guys,

So I’m a bit of a noob to this whole server-side business and everything seems to be a bit topsy-turvey!.

I am currently failing the verify because I have not included the code to throw an error if (err). The trouble is, I have no idea where to put the code (I’ve tried everywhere but have left it out of the code below for clarity purposes).

I have a very slight grasp of callbacks which is more than likely my downfall.

Here is what I currently have:

task5.js

var mymodule = require('./task5module.js');
var path = process.argv[2];
var format = process.argv[3]; 
mymodule(path, format);

task5module.js

var fs = require('fs');

module.exports = function(path, format, formatFilter) {
  format = "." + format;
  fs.readdir(path, function formatFilter(err, myData) {
  	for(var i = 0; i < myData.length; i++) {
  		var element = myData[i];
  		if(element.indexOf(format) !== -1) {
  			console.log(myData.splice(i, 1).toString());
  			i--;
  		}
  	};
  });
}

Interestingly, I also thought I wasn’t supposed to console.log the data from the module file. So I wanted to have the module file return an array and use console.log(mymodule(path, format)) in my main file but it didn’t work at all. For example:

var fs = require('fs');

module.exports = function(path, format, formatFilter) {
  format = "." + format;
  var list = [];
  fs.readdir(path, function formatFilter(err, myData) {
  	for(var i = 0; i < myData.length; i++) {
  		var element = myData[i];
  		if(element.indexOf(format) !== -1) {
  			list.push(myData.splice(i, 1).toString());
  			i--;
  		}
  	};
  });
 return list;
}

Followed by console.log(mymodule(path,format)) in the task5.js file.
But, It didn’t work, ha.

Thanks again guys.
Steve

I got it in the end thanks to the help of a fellow camper!

Is this the simplest way of doing it?

Main

 var mymodule = require('./task5module.js');
 var path = process.argv[2];
 var format = process.argv[3];

mymodule(path, format, function(err, myData) {
  for(var i = 0; i < myData.length; i++) {
    console.log(myData[i]);
  }
});

Module

var fs = require('fs');

module.exports = function(path, format, callback) {
  fs.readdir(path, function(err, myData) {
if(err) return callback(err);
format = "." + format;
var list = [];
for(var i = 0; i < myData.length; i++) {
  		var element = myData[i];
  		if(element.indexOf(format) !== -1) {
  			list.push(myData.splice(i, 1).toString());
  			i--;
  		}
};
callback(err, list);
  });
}