const jsmediatags = require('jsmediatags'); const fs = require('fs'); const INPUT = './public/audio/'; const OUTPUT = 'src/data.json'; const data = {"albums" : []}; const promises = []; try { if (fs.existsSync(INPUT)) { //file exists } else { console.log("\n============== Weband Error ====================\n\n"); console.log("Audio files are missing. Please run first : \n\n$ ./scripts/weband-init.sh \n"); console.log("\n================================================\n\n"); process.exit(1); } } catch(err) { console.log(err); process.exit(1); } function is_dir(path) { try { var stat = fs.lstatSync(path); return stat.isDirectory(); } catch (e) { // lstatSync throws an error if path doesn't exist return false; } } function id3ToJSON(path){ fs.readdirSync(path).forEach(file => { let isDir = is_dir(path + file); if(isDir) id3ToJSON(path + file + '/'); else { let filePath = path + file; if(!filePath.endsWith(".mp3") && !filePath.endsWith(".wav")) return; promises.push(new Promise((resolve, reject) => { new jsmediatags.Reader(filePath) .read({ onSuccess: (tag) => { var tags = tag.tags; if(!data.artist) data.artist = tags.artist; let album = getAlbum(tags.album); if(!album){ album = {"title": tags.album, "tracks": [], "year": tags.year} if (fs.existsSync(path + 'cover.png')) album.cover = (path + 'cover.png').replace(INPUT,'audio/'); data.albums.push(album); } let track = {"title": tags.title, "file" : filePath.replace(INPUT,'audio/')}; album.tracks.push(track); resolve(tag); }, onError: (error) => { console.log('Error'); console.log(error); reject(error); } }); })); } }); } function getAlbum(albumTitle){ for(let i = 0 ; i < data.albums.length; i++){ if(data.albums[i].title === albumTitle) return data.albums[i]; } return null; } id3ToJSON(INPUT); Promise.all(promises).then((values) => { var jsonContent = JSON.stringify(data, null, 2); console.log(jsonContent); fs.writeFile(OUTPUT, jsonContent, 'utf8', function (err) { if (err) { console.log("An error occured while writing JSON Object to File."); return console.log(err); } console.log("JSON file has been saved : " + OUTPUT); }); });