javascript - 异步读取子目录和文件没有结束
问题描述
我在 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
返回待处理的承诺,我不明白为什么请帮助我......
解决方案
forEach
您正在尝试使用不支持的 Promise 进行异步操作。您需要更改代码以使用任一for..of
循环,或者如果您可以并行执行操作,您也可以考虑使用Promise.all
.
推荐阅读
- ios - 如何在应用程序中间嵌入 SWRevealViewController 而不是在应用程序的开头快速
- java - 如何知道 Dropwizard 服务是否一启动就启动?
- java - HomePageController 中的字段 itemRepository 需要一个找不到的 ItemRepository 类型的 bean
- dynamic - Stella Architect - 系统动力学 - 重置平滑和延迟功能
- php - 使用 Excel 插入数据 - laravel 5.6
- android - 无法使用毕加索缓存图像
- selenium - Selenium Grid:RemoteWebDriver 中的 URL(url,大写)
- c# - 如何解决 Azure “此版本的 SQL Server 不支持 Windows 登录”?
- javascript - 如何动态使用 v-model 和 v-select
- python - 在 PyCharm 中使用 Cython - 如何运行已编译的文件