0

I am trying to push the file into the array named FileName however when I try to console.log(FileName) all I get is the empty array! Any input would be greatly appreciated!


const fs = require("fs");
const mm = require("music-metadata");
const dataFolder = "../../Songs";
const util = require("util");
//requiring path and fs modules
const path = require("path");
let FileName = [];
fs.readdir(dataFolder, (err, files) => {
  files.forEach(e => {
    return mm.parseFile(`../../Songs/${e}`).then(metadata => {
      // console.log(`../..Songs/${e}`);
      FileName.push(e);
      // console.log(
      //   util.inspect(metadata.common.title, {
      //     showHidden: false,
      //     depth: null
      //   })
      // );
    });
  });
});
console.log(FileName);
// mm.parseFile(
//   "/Users/nathangriffith/Desktop/dashboard/Songs/04 Smoke and Mirrors.m4a"
// )
//   .then(metadata => {
//     console.log(
//       metadata.native.iTunes[0].value
//     );
//   })
//   .catch(err => {
//     console.error(err.message);
//   });




1
  • Wait, do you just need the value from the readdir call in the FileName array? That's what you're doing when you call FileName.push(e);. However, I'll post an answer assuming that you need metdata in the FileName array... Commented Jan 30, 2020 at 0:56

2 Answers 2

1

Assuming that you need metadata in your FileName array:

const files = readdirSync(dataFolder); // Now files is an array of file names

Promise
  .all(files.map(file => mm.parseFile(`../../Songs/${file}`)
  .then(metadataArr => {
    console.log(metadataArr); // This should be your parsed metdatas
  });
Sign up to request clarification or add additional context in comments.

Comments

0

You are running an async function and expecting it to complete before the next line (console.log) runs. The log runs during the runtime of readdir, and therefore prints the value of FileName as it is before readdir changes it.

You can either change the program to use await/async correctly, or implement readdirSync instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.