从文件夹内的文件夹读取文件
问题描述:
因此,基本上我有一个文件夹,其中包含其他文件夹,每个文件夹都有自己的一组图像,我想在'ul'
中显示。问题是因为我使用的是readdir
,这是async
,我该如何编写response
,而没有得到“在.end()
之后写入错误”。这是我的代码的样子。从文件夹内的文件夹读取文件
var fs = require('fs'),
url = require('url');
module.exports = function(req, res) {
req.pathName = req.pathName || url.parse(req.url).pathname;
if(req.pathName === '/gallery') {
fs.readdir('./content/images/public', function(err, filenames) {
if (err) {
console.log(err);
return;
}
if(filenames.length) {
var list_content = '';
for (var i = 0; i < filenames.length; i++) {
fs.readdir('./content/images/public/' + filenames[i], function(err, images) {
if (err) {
console.log(err);
return;
}
for (var i = 0; i < images.length; i++) {
list_content += '<li><a href="/gallery/details/'+ i +'">' + images[i] + '</a></li>';
}
var list = '<ul>' + list_content + '</ul><a href="/">Go back to homepage</a>';
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.send(list);
});
}
} else {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write('<p>There are no images in the gallery</p><a href="/">Go back to homepage</a>');
res.end();
}
});
} else {
return true;
}
}
res.end();
}
});
答
而不是使用res.write()和res.end(),请尝试使用res.send(),这样对于你做的。更新:另外,请确保此代码位于请求回调中,其中req和res对象正确解析。
for (var i = 0; i < images.length; i++) {
list_content += '<li><a href="/gallery/details/'+ i +'">' + images[i] + '</a></li>';
}
var list = '<ul>' + list_content + '</ul><a href="/">Go back to homepage</a>';
res.send(list);
然后在前端,接收它在Ajax响应回调,像
$.post('xxxx', function(response){
alert(response); //list
});
更新:看到你更新的代码后,
module.exports = function(req, res) {
没有道理,它需要就像
exports.functionName = function(req,res){
阅读本
https://www.sitepoint.com/understanding-module-exports-exports-node-js/
module.exports是功能一个对象。不是一个功能。它看起来像这样
module.exports = {
funcExample: function() {
return 2;
},
funcOtherExample: function() {
return 1;
}
我得到一个错误,说“res.send()”不是函数 –
好的。那一定是因为你不在路由中调用这个异步函数?如果你的功能(请求,水库)?请显示更多的周边代码,并看看。 –
我编辑了我的问题,把所有的代码放在我的.js文件中 –