M.D M.D - 3 months ago 11
Javascript Question

JavaScript Function should return array

I am trying to retrieve a particular type of files from a folder in JavaScript. I am using Regex and module 'fs' for it.
The function I am trying to build doesn't return anything.I can see the array once I print it, but I am not able to return it. What I want is that the function should return an array of names of those particular files.
Here is the code

var fs = require('fs');
var dir = '/../../';
var ext = 'yml';
function test1 () {
var c = new Array();
fs.readdir(dir, function (err, list) {
var re = new RegExp("^.*\." + ext + "$");
list.forEach(function(item) {
if(re.test(item)) {
c.push(item);
}

// return item;
});

console.log(c)

});
// return c //
}

Answer

You are two layers deep in not being able to return a value directly from your function - readdir is asynchronous and forEach doesn't return values from the supplied callback. Try readdirSync instead and use filter to remove non-matching files.

function test1() {
   var files = fs.readdirSync(dir);
   return files.filter(function(item) {
      return re.test(item);
   });
}

Or more succintly:

function test1() {
   return fs.readdirSync(dir).filter(re.test);
}