[我想知道我通过使用Azure函数通过JSON响应上传的.txt文件中的内容。我能够读取文件名和类型,但也想在JSON响应中将文件转换为字符串。但是当前数据响应仍然为空:
{
"name": "20200429112846_-_IB_records.txt",
"type": "text/plain",
"data": ""
}
我的代码是:
var multipart = require("parse-multipart");
module.exports = function (context, request) {
// encode body to base64 string
var bodyBuffer = Buffer.from(request.body);
var boundary = multipart.getBoundary(request.headers['content-type']);
// parse the body
var parts = multipart.Parse(bodyBuffer, boundary);
var fileContent = "";
var fileBuffer = Buffer.from(parts[0].data);
var fs = require('fs');
fs.readFile(fileBuffer, 'utf8', function(err, data) {
if (err) throw err;
fileContent = data;
});
context.res = { body : { name : parts[0].filename, type: parts[0].type, data: fileContent}};
context.done();
};
有人知道吗?
fs.readFile
异步运行,所以
context.res = { body : { name : parts[0].filename, type: parts[0].type, data: fileContent}};
context.done();
在实际读取文件之前执行。解决此问题的一种方法是将context
-stuff放入readFile回调中:
fs.readFile(fileBuffer, 'utf8', function(err, data) {
if (err) throw err;
fileContent = data;
context.res = { body : { name : parts[0].filename, type: parts[0].type, data: fileContent}};
context.done();
});