Read file in folder javascript

For all example below you need to import fs and path modules:

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

Read files asynchronously

function readFiles(dir, processFile) {
  // read directory
  fs.readdir(dir, (error, fileNames) => {
    if (error) throw error;

    fileNames.forEach(filename => {
      // get current file name
      const name = path.parse(filename).name;
      // get current file extension
      const ext = path.parse(filename).ext;
      // get current file path
      const filepath = path.resolve(dir, filename);

      // get information about the file
      fs.stat(filepath, function(error, stat) {
        if (error) throw error;

        // check if the current path is a file or a folder
        const isFile = stat.isFile();

        // exclude folders
        if (isFile) {
          // callback, do something with the file
          processFile(filepath, name, ext, stat);
        }
      });
    });
  });
}

Usage:

// use an absolute path to the folder where files are located
readFiles('absolute/path/to/directory/', (filepath, name, ext, stat) => {
  console.log('file path:', filepath);
  console.log('file name:', name);
  console.log('file extension:', ext);
  console.log('file information:', stat);
});

Read files synchronously, store in array, natural sorting

/**
 * @description Read files synchronously from a folder, with natural sorting
 * @param {String} dir Absolute path to directory
 * @returns {Object[]} List of object, each object represent a file
 * structured like so: `{ filepath, name, ext, stat }`
 */
function readFilesSync(dir) {
  const files = [];

  fs.readdirSync(dir).forEach(filename => {
    const name = path.parse(filename).name;
    const ext = path.parse(filename).ext;
    const filepath = path.resolve(dir, filename);
    const stat = fs.statSync(filepath);
    const isFile = stat.isFile();

    if (isFile) files.push({ filepath, name, ext, stat });
  });

  files.sort((a, b) => {
    // natural sort alphanumeric strings
    // https://stackoverflow.com/a/38641281
    return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
  });

  return files;
}

Usage:

// return an array list of objects
// each object represent a file
const files = readFilesSync('absolute/path/to/directory/');

Read files async using promise

More info on promisify in this article.

const { promisify } = require('util');

const readdir_promise = promisify(fs.readdir);
const stat_promise = promisify(fs.stat);

function readFilesAsync(dir) {
  return readdir_promise(dir, { encoding: 'utf8' })
    .then(filenames => {
      const files = getFiles(dir, filenames);

      return Promise.all(files);
    })
    .catch(err => console.error(err));
}

function getFiles(dir, filenames) {
  return filenames.map(filename => {
    const name = path.parse(filename).name;
    const ext = path.parse(filename).ext;
    const filepath = path.resolve(dir, filename);

    return stat({ name, ext, filepath });
  });
}

function stat({ name, ext, filepath }) {
  return stat_promise(filepath)
    .then(stat => {
      const isFile = stat.isFile();

      if (isFile) return { name, ext, filepath, stat };
    })
    .catch(err => console.error(err));
}

Usage:

readFiles('absolute/path/to/directory/')
  // return an array list of objects
  // each object is a file
  // with those properties: { name, ext, filepath, stat }
  .then(files => console.log(files))
  .catch(err => console.log(err));

Note: return undefined for folders, if you want you can filter them out:

readFiles('absolute/path/to/directory/')
  .then(files => files.filter(file => file !== undefined))
  .catch(err => console.log(err));

Read file in folder javascript

node.js fs

Do you need to get all files present in the directory or you want to scan a directory for files using node.js, then you’re on the correct web page because in this Nodejs How to Tutorial, we will learning How to get the list of all files in a directory in Node.js.

We will be using Node.js fs core module to get all files in the directory, we can use following fsmethods.

  • fs.readdir(path, callbackFunction) — This method will read all files in the directory.You need to pass directory path as the first argument and in the second argument, you can any callback function.
  • path.join() — This method of node.js path module, we will be using to get the path of the directory and This will join all given path segments together.

Steps to get list of all the files in a directory in Node.js

  1. Load all the required Nodejs Packages using “require”.
  2. Get the path of the directory using path.join() method.
  3. Pass the directory path and callback function in fs.readdir(path, callbackFunction) Method.
  4. The callback function should have error handling and result handling logic.
  5. inside callback function handle the error and run forEach on the array of files list from the directory.
  6. Apply your logic for each file or all the files inside the forEach function.

Full code:

first appeared on Web Development Blog StackFrame.

How do you read all files from a folder in JS?

js fs core module to get all files in the directory, we can use following fsmethods. fs. readdir (path, callbackFunction) — This method will read all files in the directory. You need to pass directory path as the first argument and in the second argument, you can any callback function.

Can JavaScript read a local file?

JavaScript cannot typically access local files in new browsers, but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.

How do I read a folder in node JS?

The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory.

How do you load a file in JavaScript?

To load a JavaScript file dynamically: Create a script element..
src : the file path..
type : file type - "text/javascript".
async : if we set async to false , then the file will be loaded and executed first before proceeding to the next action..