Home > Back-end >  Get file paths in a directory with javascript
Get file paths in a directory with javascript

Time:09-17

I'm trying to create an npm package that checks for images not imported.

How do I direct javascript to loop through a directory and pass the file paths into an array?

I then want to loop through another directory and check if those files contain the file path as a string.

I just can't seem to find any examples of extracting file paths dynamically from a directory, and I'd appreciate any guidance.

CodePudding user response:

with node you would do something like:

const path = require("path");
const fs = require("fs");

const directoryPath = path.join(__dirname, ...path to your dir);

const filePaths = [];

fs.readdir(directoryPath,(err, files) => {
    if (err) {
        return console.log('Unable to scan directory: '   err);
    } 

    files.forEach(file =>{
        filePaths.push(path.resolve(file));
    })
})

you now have an array with the filePaths and can do your other tasks with it. If you don't want the full filepath but just the names just push the file instead of path.resolve(file)

  • Related