I want to know the content from a.txt file I upload via the JSON response with an Azure function. I'm able to read the filename and type, but also want to convert the file to a string in my JSON response. But currently the response in data stays empty:
{
"name": "20200429112846_-_IB_records.txt",
"type": "text/plain",
"data": ""
}
My code is:
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();
};
Anyone got an idea?
fs.readFile
operates asynchronously, so
context.res = { body : { name : parts[0].filename, type: parts[0].type, data: fileContent}};
context.done();
is executed before the file has actually been read. One way to solve this is to put the context
-stuff in the readFile callback:
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();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.