Home > Software engineering >  returning values from fs.readdir by using Promise in node js /javascript
returning values from fs.readdir by using Promise in node js /javascript

Time:02-26

function fileType() {
  return new Promise((resolve, reject) => {
    let Fields = fs.readdir(
      path.resolve(__dirname, "access"),
      (err, files) => {
        if (err) {
          reject(err);
          return;
        } else {
          files.map((file) => {
            return file.split(".").slice(0, -1).join(".");
          });
        }
      }
    );
    resolve(Fields);
  });
}

async function ambitious(data) {
  let fields = [];

  if (data.collections) {
   fields= await fileType();
  } else {
     if(data.types.access){
       fields.push(data.config.access);
     }
     else{
      fields= await fileType();
     }
  }

  return {
    data_name: data.name,
    data_access: data.config,
    data_encrypted: data.encrypt,
    data_fields: fields,
  };
}

Here I am trying to return field value from the if statement and store it in the data_fields

here problem is I am getting the values from the else statement but when I am trying to return value from If statement its showing undefined

As I want to read all the files which are present inside the access and remove the file extension and as an array I want to store it in data_fields

for eg if files are present inside access

let files=[ 'config.sql','admin.xml', 'user_manual.txt' ]

for that purpose I used split and slice to remove all the extension and return data in array format in data_fields

I don't know how to return value from fs.readdir and store it in data_fields

CodePudding user response:

Node already offers a Promise version of the fs API. You don't need to wrap the callback version in a Promise.

import { promises } from "fs";

async function fileType () {
    let files = await promises.readdir(path.resolve(__dirname, "access"));
    return files.map( file => file.split(".").slice(0, -1).join("."));
}

CodePudding user response:

Try like this

function fileType() {
  return new Promise((resolve, reject) => {
    let Fields = fs.readdir(
      path.resolve(__dirname, "access"),
      (err, files) => {
        if (err) {
          reject(err);
        } else {
          resolve(files.map((file) => { // resolve here
            return file.split(".").slice(0, -1).join(".");
          }))
        }
      }
    );
    // if you resolve you promise here, you resolve it before the readdir has been resolved itself.
  });
}
  • Related