问题描述
在这种情况下,我试图发送带有文件内容的请求,但是问题是内容到达时未定义。我该如何解决?我尝试了stackoverflow的多个版本,但到目前为止没有任何效果。
const ifExists = (filePath) => {
try {
if (fs.existsSync(filePath)) {
return true;
}
} catch (err) {
console.log(err);
}
return false;
}
const readMyFile = async (filePath) => {
const fileExists = ifExists(filePath);
if (fileExists) {
fs.readFile(filePath,(err,data) => {
if (err) {
console.log("Error occurred when trying to read the file.");
return false;
}
console.log("File successfully read.");
return data; // data has the right content here
});
} else {
console.log("File not found");
return false;
}
}
const getFile = async function (req,res,next) {
try {
const content = await readMyFile(filePath); // the content is undefined here
res.writeHead(200,{ "Content-Type": "application/json" });
res.write(JSON.stringify(content));
} catch (err) {
console.log("Error occurred.");
res.status(500).send("Error");
} finally {
res.end();
}
};
谢谢您的时间!
解决方法
fs.readFile
使用回调,并且不返回promise,这意味着它不能在异步函数中正确使用。如果您要使用异步功能,建议您返回一个Promise。
const readFile = async (filePath) => {
return new Promise((resolve,reject) => {
if (!exists(filePath)) {
reject(Error("File not found"));
}
fs.readFile(filePath,(err,data) => {
if (err) {
reject(err);
}
resolve(data)
});
})
}