M.D M.D - 1 year ago 79
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)) {

// return item;


// return c //

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download