簡體   English   中英

循環遍歷 mp3 文件名數組並將 id3 標簽提取到 nodejs 中的另一個數組

[英]Loop through array of mp3 filenames and extract id3 tags in to another array in nodejs

function extractId3(value, index, list) {
  if (path.extname(value) === '.mp3') {
    id3js({ file: '/Users/user/materialApp/client/songs/' + value, type: id3js.OPEN_LOCAL }, function(err, tags) {
      return tags.v2.image;
    });
  }
}

exports.index = function(req, res) {
  fs.readdir('/Users/user/materialApp/client/songs', function(err, files) {
    images = _.map(files, extractId3);
    console.log(images);
    res.json(files);
  });
};

我對 Web 開發和 nodejs 的異步性質相當陌生。

我試圖遍歷我在 fs.readdir() 之后獲得的所有 mp3 文件並從中提取 id3 標簽。

console.log(images)產生[]

我無法理解如何處理id3js()的異步性質。 提取此信息並將其作為對此 http 請求的響應傳遞的正確方法是什么。

使用 Pluck

勇氣_.pluck(列表,propertyName的)什么是可能是最常見的用例為圖個方便版本:提取屬性值的列表。

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}]; _.pluck(stooges, 'name'); => [“萌”,“拉里”,“卷曲”]

images = _.pluck(files, extractId3);

我可以讓它工作的唯一方法是使用遞歸:

exports.index = function(req, res) {
  var info = new Array();
  fs.readdir('/Users/user/materialApp/client/songs', function(err, files) {
    var mp3s = uscore.filter(files, function(file) { if(path.extname(file) === '.mp3') return file});
    var ID = 0;
    console.log(mp3s.length);
    if (ID < mp3s.length) 
        extractId3(mp3s[ID]);
    else 
        console.log(info);

    function extractId3(file) {
      id3js({ file: '/user/user/materialApp/client/songs/' + file, type: id3js.OPEN_LOCAL }, function(err, tags) {
        if(tags.title) {
          console.log(tags.v1);
          info.push({'file': file, 'title':tags.title, 'album':tags.album, 'year':tags.year});
        }
        ID++;
        if (ID < mp3s.length)
          extractId3(mp3s[ID]);
        else {
          res.json(info);
        }
      });
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM