简体   繁体   English

如何使用nodejs推入数组

[英]How to push into an array using nodejs

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!我试图将文件推送到名为FileName的数组中,但是当我尝试使用console.log(FileName)我得到的只是空数组! 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);
//   });




Assuming that you need metadata in your FileName array:假设您需要FileName数组中的metadata

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

You are running an async function and expecting it to complete before the next line (console.log) runs.您正在运行一个异步函数并期望它在下一行 (console.log) 运行之前完成。 The log runs during the runtime of readdir, and therefore prints the value of FileName as it is before readdir changes it.日志readdir 运行时运行,因此打印 FileName 的值,因为它readdir 更改它之前

You can either change the program to use await/async correctly, or implement readdirSync instead.您可以更改程序以正确使用 await/async,或者改为实现 readdirSync。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM