Unhandled rejection TypeError: path.extname is not a function

Unhandled rejection TypeError: path.extname is not a function

我正在尝试编写一个函数,遍历目录的内容并 returns 目录中的所有 xml 文件。到目前为止,我能够 return 目录中的所有文件(console.log(files) 打印出带有文件名的字符串数组,但是当我尝试使用 path.extname 函数进行过滤时,我得到:

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)

这是我的代码:

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

您将 path 用于两种不同的事物,并且它们相互干扰。您有一个全局模块:

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

...但是你 shadow 那有一个论点:

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

所以在 getFileNames 中,path 标识符指的是那个参数,而不是你的全局变量,因为它不指代 path 模块(从上下文来看,我'我猜 path 参数是一个字符串),你没有 path.extname.

使用不同的名称。