Ben Beri
Ben Beri

Reputation: 1201

NodeJS read multiple files blocking and return express response

I am retrieving a route, and then I am getting all the json files I need from a directory.

I need to merge all of these json files into one json object by key-value, where the key is the file name, and value is the file content.

I need to make it async because if not, the response will be sent before the file system finishes its job, and I will have an empty json object response.

I tried using Promise.all with await:

  app.route("/pull").get(async function(req, res) {
      fs.readdir(path, async (error, files) => {      
        if (error) {
          console.log("Could not load files. ", error.message);
          res.sendStatus(500);
        }
        else {

          let json = {};

          json = await Promise.all(
              files.map(async (fileName, index) => {

                return await fs.readFile(path + fileName, 'utf-8', (err, content) => {

                    return {key: fileName, value : JSON.parse(content)}

                });

              })

          );

          res.status(200).json(json);
        }
    });
  });

I am getting [null] as a response, what did I miss?

Upvotes: 0

Views: 137

Answers (1)

Christian
Christian

Reputation: 7852

The route handler doesn't wait for fs.readdir for completing its callback. You need to promisify readdir like so:

import fs from 'fs';
import {promisify} from 'util';
const readdir = promisify(fs.readdir);

and then in the handler:

{error, files} = await readdir(...)
...

Upvotes: 1

Related Questions