Domanda

I'm a begginer in Node JS and I'm trouble trying to build a JSON object.

I've found a module to find the metadata of a mp3 file and I want to store this information on a JSON obj.

The behaviour of my applicaiton is the following:

  1. Read my "music" directory.
  2. For each file on the directory, extract his info and store it in the structure "jsonSong". Push the "jsonSong" into structure called "jsonObj".
  3. Make a console.log of "jsonObj" to see the result.

Here's the code:

var fs = require('fs');
var mm = require('musicmetadata');

fs.readdir('./music/', function(err,files) {
    if(err) throw err;
    var jsonObj = {
                    songs: []
                };
    files.forEach(function(file){
        var jsonSong = { 
                        title:"",
                        artist:"",
                        duration:"",
                        pic:""
                    }
        var parser = new mm(fs.createReadStream('./music/'+file));
        parser.on('title', function(result) {
            jsonSong.title = result;
        });
        parser.on('albumartist', function(result) {
            jsonSong.artist = result;
        });
        parser.on('duration', function(result) {
            jsonSong.duration = result;
        });
        parser.on('picture', function(result) {
            jsonSong.pic = result;
        });

        jsonObj.songs.push(jsonSong);
    });
    console.log(jsonObj);
});

My problem here is that "jsonSong" seems to be empty, here's the result of the last console.log (I have 3 songs on my music dir, so i have 3 entrys on the structure):

{ songs: 
   [ { title: '', artist: '', duration: '', pic: '' },
     { title: '', artist: '', duration: '', pic: '' },
     { title: '', artist: '', duration: '', pic: '' } ] }

Thanks for your time.

È stato utile?

Soluzione

You have to wait for the callbacks to execute before the data gets populated, you can use the done event.

parser.on('done', function (err) {
  console.log(jsonObj);
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top