首页 > 解决方案 > 异步读取子目录和文件没有结束

问题描述

我在 javaScript 中为 nodeJS 本地服务器编写了函数,它使用承诺异步读取目录,但在函数服务器结束后不执行“respones.end()”函数:

// import http module
const http = require('http');
// import fs module
const fs = require('fs');
// declaration of the rood directory path
const rootPath = '.';

//function which reads files recursively in the sub-directories using promises
//the function takes 'response' from server response object and 'path' is argument for sub-folder directory location
const readFilesRecursively = (response, path = rootPath) => {
    //function returns promise
    return new Promise((resolve) => {
        //in the promise we read directory files Asynchronously
        fs.readdir(path, (err, files) => {
            files.forEach(
                file => {
                    // check Synchronously if the path is directory
                    let checkDir = fs.lstatSync(path + '/' + file).isDirectory();
                    //predefine new empty promise
                    let promiseToReturn = Promise.resolve();
                    //check if the path is directory
                    if (checkDir === true) {
                        //print path
                        response.write(path + '/' + file + "\n");
                        //call the function recursively for sub-directory
                        return promiseToReturn.then(_ => readFilesRecursively(response, path + '/' + file));
                    } else {
                        //print file path
                        response.write(path + '/' + file + "\n");
                        //return empty promise
                        return promiseToReturn;
                    }
                }
            );

        });
    })
};
//initialising server
const server = http.createServer((req, res) => {
    //printing request url
    res.write("you have required: " + req.url + "\n");
    //declare promise variable
    let endPromise = readFilesRecursively(res); // <--- endPromise is pending infinitely
    //after function returns the promise
    endPromise.then(
        () => {
            //end server response
            res.end("reading finished successfully!!!");
        }
    );

});

//listening port
server.listen(3000);
//printing some text
console.log("listening the port 3000...");

该函数readFilesRecursively返回待处理的承诺,我不明白为什么请帮助我......

标签: javascriptnode.js

解决方案


forEach您正在尝试使用不支持的 Promise 进行异步操作。您需要更改代码以使用任一for..of循环,或者如果您可以并行执行操作,您也可以考虑使用Promise.all.


推荐阅读