我是新手。我有一组图像,并且想在页面加载时将其显示在客户端浏览器上。
有可能吗?
我现在只能发送一个文件,但不能发送多个文件,现在我被困住了,有人可以帮我吗。
感谢帮助
router.get('/getList', function(req, res, next) {
var fileNames = [];
fileNames = readDir.readSync('/NodeWorkspace/uploads/output/', ['**.png']);
var data = {};
fileNames.forEach(function(filename) {
filepath = path.join(__dirname, '../../uploads/output') + '/' + filename;
fs.readFile(path.join(__dirname, '../../uploads/output') + '/' + filename, function(err, content) {
if (!err) {
console.log(content);
}
});
});
//res.sendFile(path.join(__dirname,'../../uploads/output/', fileNames[0]));
response.data = fileNames;
res.json(response);
});
答案 0 :(得分:0)
将fs回调转换为Promise,并在完成发送响应后读取所有并行数据。
const fs = require('fs');
const db = require('../db');
const readFile = util.promisify(fs.readFile);
router.get('/getList', function (req, res, next) {
var fileNames = [];
fileNames = readDir.readSync('/NodeWorkspace/uploads/output/', ['**.png']); // use async function instead of sync
var data = {};
const files = fileNames.map(function (filename) {
filepath = path.join(__dirname, '../../uploads/output') + '/' + filename;
return readFile(filepath); //updated here
});
Promise.all(files).then(fileNames => {
response.data = fileNames;
res.json(response);
}).catch(error => {
res.status(400).json(response);
});
});