Miha Šušteršič Miha Šušteršič - 20 days ago 9
Javascript Question

Unhandled rejection TypeError: path.extname is not a function

I am trying to write a function that goes trough the content of a directory and returns all the xml files inside the directory. So far I am able to return all the files in the directory (

console.log(files)
prints out an array of strings with the file names, but when I try to filter with the
path.extname
function I am getting:


usr/local/Cellar/node/6.8.0/bin/node
/Users/shooshte/Sportradar/notThatKindOfPeon/bluebird.js Unhandled
rejection TypeError: path.extname is not a function
at /Users/shooshte/Sportradar/notThatKindOfPeon/bluebird.js:23:31
at Array.filter (native)
at /Users/shooshte/Sportradar/notThatKindOfPeon/bluebird.js:22:30
at tryCatcher (/Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/promise.js:510:31)
at Promise._settlePromise (/Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/promise.js:567:18)
at Promise._settlePromise0 (/Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/promise.js:612:10)
at Promise._settlePromises (/Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/promise.js:691:18)
at Promise._fulfill (/Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/promise.js:636:18)
at /Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/nodeback.js:42:21
at FSReqWrap.oncomplete (fs.js:123:15)


This is my code:

const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const path = require('path');

function getFileNames(path) {
// Read content of path
return fs.readdirAsync(path)
// For every file in path
.then(function(content) {
// Filter out the directories
return content.filter(function(file) {
return fs.statSync(path + '/' + file).isDirectory();
});
})
// For every directory
.then(function(directories) {
directories.map(function(directory) {
// Read file in the directory
fs.readdirAsync(path + '/' + directory + '/')
.then(function(files) {
// Filter out the XMLS
return files.filter(function(file) {
return path.extname(file) == '.XML';
});
console.log(files);
});
});
});
}

getFileNames('./XML');

Answer

You're using path for two different things, and they're interfering with each other. You have a module global:

const path = require('path');
// ---^

...but then you shadow that with an argument:

function getFileNames(path) {
// -------------------^

So within getFileNames, the path identifier refers to that argument, not your global, and since it doesn't refer to the path module (from context, I'm guessing the path argument is a string), you don't have path.extname.

Use different names.