[英]Read content of posted .txt file with Azure function NodeJS
我想知道我通過 JSON 響應上傳的 a.txt 文件的內容,響應為 Azure function。 我能夠讀取文件名和類型,但也想在我的 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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.