在readdir中使用readdir后如何将数据发送到客户端

时间:2019-01-17 09:53:51

标签: node.js express asynchronous promise readdir

我需要阅读一个名为“ curvas”的文件夹。 “ curvas”中有很多文件夹,我正在使用readdir来获取它们。将文件夹放入“ curvas”内部后,我正在进行一次foreach并使用readdir列出文件(“ curvas”内部的文件夹内的文件)。

问题是我只能访问内部readdir内的变量(我用console.log测试)。

问:我如何访问此变量并以res响应客户端。 ?

这是我走多远了:

exports.getInserted = async function (req, res) {

    var teste = await getFilesNames(); // HERE I NEED TO GET THIS FILES NAMES WITH FOLDERS
    console.log(teste); // AND THEM PASSING TO THE CLIENT WITH RES.SEND()

};

function getFilesNames() {
    return new Promise(function (resolve, reject) {

        const chartFolder = './curvas/';
        var fileNames = [];

        fs.readdir(chartFolder, (err, folders) => {

            if (err) {
                reject(new Error("Erro ao ler os arquivos."));
            }
            folders.forEach(folder => {
                fs.readdir(chartFolder + folder, (err, files) => {
                    fileNames = files;
                    console.log(files) // ----- HERE I CAN SEE ALL FILES AND LIST WITH THEIR FOLDERS.
                });
            });
            // I NEED USE resolve(fileNames) HERE, BUT IS EMPTY!!
        });
    });
};

谢谢!

[编辑]

解决方案:由@omarwaleed指导

    exports.getInserted = async function (req, res) {

    // Envia os arquivos das pastas de curvas para o cliente.
    var data = await getFilesNames();
    res.status(200).send(data);

};

function getFilesNames() {
    return new Promise(function (resolve, reject) {

        const chartFolder = './curvas/';

        // take care. I've turned it into an async function here
        fs.readdir(chartFolder, async (err, folders) => {

            if (err) {
                reject(new Error("Erro ao ler os arquivos."));
            }
            let promiseArray = [];
            folders.forEach(folder => {
                promiseArray.push(
                    new Promise((resolve, reject) => fs.readdir(chartFolder + folder, (err, files) => {
                        if (err) {
                            reject(err);
                        }
                        resolve({
                            folder: folder,
                            files: files
                        });
                    }))
                )
            });
            let results = await Promise.all(promiseArray);
            resolve(results)
        });
    });
};

1 个答案:

答案 0 :(得分:1)

使用resolve代替注释// I NEED USE resolve(fileNames) HERE, BUT IS EMPTY!!将导致未定义的resolve语句,因为第二个fs.readdir将异步运行,这意味着将在代码解析后读取目录。为解决此问题,我建议您将fs.readdir包含在Promise中,以在其中等待所有文件的读取并解决响应
这是您的函数的外观

function getFilesNames() {
    return new Promise(function (resolve, reject) {

        const chartFolder = './curvas/';
        var fileNames = [];

        // take care. I've turned it into an async function here
        fs.readdir(chartFolder, async (err, folders) => {

            if (err) {
                reject(new Error("Erro ao ler os arquivos."));
            }
            let promiseArray = [];
            folders.forEach( folder => {
            promiseArray.push(
              new Promise((resolve, reject)=>fs.readdir(chartFolder + folder, (err, files)=>{
                if(err){
                  reject(err)
                }
                resolve(files)
              }))
            )
        });
        let results = await Promise.all(promiseArray);
            resolve(results)
        });
    });
};