kmp4hj
kmp4hj

Reputation: 61

Javascript unknown undefined returned

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

Upvotes: 0

Views: 367

Answers (3)

CodeLama
CodeLama

Reputation: 94

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

Upvotes: 0

Alexander O'Mara
Alexander O'Mara

Reputation: 60577

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');

Upvotes: 3

Marin Takanov
Marin Takanov

Reputation: 1138

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

Hello, World!
undefined

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

Upvotes: -1

Related Questions