skip to Main Content

I am trying to read the filenames of a directory, split the individual filename into an array, then return an array with the index positions and the split filename arrays. Right now it will only read and return one file.
So far, this is what I have:

const splitString = (_str) => {
var myNewString = 
_str.split("-");
return myNewString;
} ;

const getInfo = (filePath) => {
   let tempfileInfo = [];
   let tempfileName;
   let tempfileIndex;
   fs.readdirSync(filePath).map((i, index) => {
    return {
       id: tempfileIndex = index + 1;
       filename: tempfileName = splitString(i);
        }
  }); tempfileInfo.push(tempfileIndex, tempfileName);
      console.log(tempfileInfo); //returns [20, ['9', 'YE', 'BLU', 'ITEM', '.png']]
}

I have tried adding forEach() to the .map function but that just spits out the same array repeated once then another array with it twice, etc.. until it reaches the end of the files in the directory. Also I don’t think I will actually need the returned index but if for some reason it will help with the rest of my program, I don’t understand why the index is 20 either (yes there are twenty files in the folder and I’m adding 1), the file it is pulling is directly in the center of all of the files and it’s starting the index from the back so what is .map indexing here? It’s probably something simple but for some reason I just cannot see it right now. Thanks in advance for any help!

2

Answers


  1. Chosen as BEST ANSWER

    I solved my own issue. Turns out I did not need to go that deep. This returned the correct array:

    const getInfo = (filePath) => {
      let tempfileInfo = [];
      fs.readdirSync(filePath).forEach(file => {
      tempfileInfo.push(tempfileName);
      console.log(tempfileInfo);
    });
    }
    

  2. You already have a solution inside your code.

    Array.map return a new Array, you just only have to assign it a variable.

    const splitString = (_str) => {
       var myNewString =  _str.split("-");
       return myNewString;
    } ;// It's a simple split, you don't need any separate function indeed
    
    const getInfo = (filePath) => {
      //let tempfileInfo = [];
      //let tempfileName;
      //let tempfileIndex;
      const tempfileInfo = fs.readdirSync(filePath).map((fname,index) => {
         return {
           id: ++index,
           filename: fname.split("-")
         }
       }); 
    
     //tempfileInfo.push(tempfileIndex, tempfileName);
      console.log(tempfileInfo);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search