循环播放mp3文件名并将id3标签提取到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的asynchronous性质相当陌生。

我试图循环播放fs.readdir()之后的所有mp3文件,并从中提取id3标签。

console.log(images)产生[]

我无法理解如何处理id3js()的asynchronous性质。 什么是正确的方式来提取这些信息,并将其作为对这个http请求的响应来传递。

使用Pluck

pluck _.pluck(list,propertyName)可能是map最常用的一个方便的版本:提取属性值列表。

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

 images = _.pluck(files, extractId3); 

我能得到它的唯一方法是使用recursion:

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