0

I keep getting undefined returned when I run this code:

var fs = require('fs'),
    path = require('path'),
    filepath = process.argv[2];

function listFilesByExtension(path_to_file, ext) {
    fs.readdir(path_to_file, function (err, files) {
        if (err) {
            console.log(err);
        } else {
            console.log(files);
        }
    });
}

console.log(listFilesByExtension(filepath, 'txt'));

the console.log(files) returns:

undefined
[ 'CHANGELOG.md',
  'LICENCE.md',
  'README.md',
  'api.html',
  'dat',
  'data.dat',
  'data.json',
  'learnyounode.dat',
  'learnyounode.sql',
  'learnyounode.txt',
  'md',
  'w00t.dat',
  'w00t.txt',
  'words.dat',
  'wrrrrongdat' ]

So the undefined is not from there, console.log(err) is also return null.

Can anybody explain to me why this is happen? thank you

kmp4hj
  • 61
  • 6

3 Answers3

3

This is because your listFilesByExtension function does not return anything, so your console.log for this function call will output undefined.

This line is the cause:

console.log(listFilesByExtension(filepath, 'txt'));

If you remove the console.log form this line, you're unexpected undefined will go away.

listFilesByExtension(filepath, 'txt');
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
0

The function listFilesByExtension() does return undefined because there isn't any return statement. There is also called asynchronous function so this code will never return what you want.

You should try synchronous function https://nodejs.org/api/fs.html#fs_fs_readdirsync_path

eg:

function listFilesByExtension(path, ext) {
    var filtered,
        dirContent = fs.readdirSync(path);

    // do your filtering by extension here.
    // The filtered will be an Array of paths filtered out from the dirContent
    return filtered;
}

NOTE: there isn't any error handling if the path does not exists

Community
  • 1
  • 1
CodeLama
  • 94
  • 5
-1

If you write in the browser console: console.log('Hello, World!'); it will print

Hello, World!
undefined

That's because console.log(); returns undefined.

Marin Takanov
  • 1,079
  • 3
  • 19
  • 36
  • While all of this is true, they would only see this if they ran this code interactively, in which case they would see `undefined` twice. P.S. Not the downvoter. – Alexander O'Mara Nov 04 '15 at 07:24