2013-12-19 24 views
0

我有一個文件數組,我試圖得到文件的basename,沒有它們的長擴展名。這是什麼樣的陣列看起來像一個例子:Node.js:使用path.basename時,目錄沒有方法'basename'

[ 
    '/public/uploads/contentitems/.DS_Store', 
    '/public/uploads/contentitems/063012A5-60BC-4A4C-AEC2-56B0D5D99EF0/063012A5-60BC-4A4C-AEC2-56B0D5D99EF0.png', 
    '/public/uploads/contentitems/063012A5-60BC-4A4C-AEC2-56B0D5D99EF0/063012A5-60BC-4A4C-AEC2-56B0D5D99EF0_1.png', 
    '/public/uploads/contentitems/2A431412-A776-4D11-841A-B640DF37C9E2/2A431412-A776-4D11-841A-B640DF37C9E2_2.png' 
] 

我想:

[ 
    '.DS_Store', 
    '063012A5-60BC-4A4C-AEC2-56B0D5D99EF0/063012A5-60BC-4A4C-AEC2-56B0D5D99EF0.png', 
    '063012A5-60BC-4A4C-AEC2-56B0D5D99EF0/063012A5-60BC-4A4C-AEC2-56B0D5D99EF0_1.png', 
    '2A431412-A776-4D11-841A-B640DF37C9E2/2A431412-A776-4D11-841A-B640DF37C9E2_2.png' 
] 

根據該文檔時,path.basename函數應該返回我的文件不帶路徑。

但我得到的是以下錯誤:

TypeError: Object /public/uploads/contentitems has no method 'basename' 

這裏是我使用的是現在的代碼:我在我的文件的頂部使用path = require('path');以及

var walk = function(dir, done) { 
     var results = []; 
     fs.readdir(dir, function(err, list) { 
      if (err) return done(err); 
      var pending = list.length; 
      if (!pending) return done(null, results); 
      list.forEach(function(file) { 
       file = dir + '/' + file; 
       fs.stat(file, function(err, stat) { 
        if (stat && stat.isDirectory()) { 
         walk(file, function(err, res) { 
          results = results.concat(res); 
          if (!--pending) done(null, results); 
         }); 
        } else { 
         var suffix = getSuffix(file); 
         if (!verObj[suffix]) results.push(file); 
         if (!--pending) done(null, results); 
        } 
       }); 
      }); 
     }); 
    }; 

    walk(path, function(err, results) { 
     if (err) throw err; 
     results.forEach(function(file) { 
      console.log(path.basename(file)); 
     }); 
     self.respond({files: results}, {format: 'json'}); 
    }); 

+0

你確定它不是第一個導致問題的'.DS_Store'? – adeneo

回答

5

path有變量名稱衝突。

使用path以外的其他值來表示您想要走的目錄。

walk(path, function(err, results) { 

你傳入一個名爲pathwalk()字符串。

console.log(path.basename(file)); // <-- path is a string here 
+0

啊,廢話,謝謝! :S – Neil

相關問題