Marcus
Marcus

Reputation: 45

JS Get properties from many files at once

What I have: 50 mp3 files in a folder. What I want to do: Create an object for every file that includes name and src.

What I don't know how to do is select and get properties from all of the files. Is it even possible? I know that you can get info from a text file via JS.

It would maybe be something like:

for (var i = 0; i < musicFolder.length; i++) {
 var object = new Object (
 musicFolder[i].title,
 musicFolder[i].path/src
 );
 objectArray.push(object);
}

I would perhaps need to select an entire folder, but I dont know how to do this is JS.

Upvotes: 0

Views: 41

Answers (1)

Hussain Ali Akbar
Hussain Ali Akbar

Reputation: 1655

Assuming that you are running this in Node.js and you only need the name and the path of the file, you can do this:

var fs = require('fs');
path = 'your path here';
const res = [];
fs.readdir(path, (err, items) => {
  for (var i=0; i<items.length; i++) {
    res.push({
      name: items[i],
      src: `${path}/${items[i]}`
    });


  }
  console.log(res)
});

This will iterate your folder and list all the files in it. Then it will save the name of the file and its path in a object and push it to an array.

Upvotes: 1

Related Questions