我正在尝试编写一个通过目录内容的函数,并返回目录中的所有xml文件。到目前为止,我能够返回目录中的所有文件(console.log(files)
打印出带有文件名的字符串数组,但是当我尝试使用path.extname
函数进行过滤时,我得到了:
USR /本地/地窖/节点/ 6.8.0 / bin中/节点 /Users/shooshte/Sportradar/notThatKindOfPeon/bluebird.js未处理 rejection TypeError:path.extname不是函数 at /Users/shooshte/Sportradar/notThatKindOfPeon/bluebird.js:23:31 at Array.filter(native) at /Users/shooshte/Sportradar/notThatKindOfPeon/bluebird.js:22:30 在tryCatcher(/Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/util.js:16:23) 在Promise._settlePromiseFromHandler(/Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/promise.js:510:31) 在Promise._settlePromise(/Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/promise.js:567:18) 在Promise._settlePromise0(/Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/promise.js:612:10) 在Promise._settlePromises(/Users/shooshte/Sportradar/notThatKindOfPeon/node_modules/bluebird/js/release/promise.js:691:18) 在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 在FSReqWrap.oncomplete(fs.js:123:15)
这是我的代码:
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');
答案 0 :(得分:1)
你正在使用path
两个不同的东西,他们互相干扰。你有一个全球模块:
const path = require('path');
// ---^
...但是 shadow 带有参数:
function getFileNames(path) {
// -------------------^
因此在getFileNames
内,path
标识符引用该参数,而不是您的全局,并且因为它没有引用path
模块(从上下文,我猜path
参数是一个字符串),你没有path.extname
。
使用不同的名称。