【问题标题】:Read content of posted .txt file with Azure function NodeJS使用 Azure 函数 NodeJS 读取发布的 .txt 文件的内容
【发布时间】:2020-04-30 19:09:03
【问题描述】:

我想知道我通过带有 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();  
};

有人有想法吗?

【问题讨论】:

    标签: node.js azure-functions filereader


    【解决方案1】:

    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();  
        });
    

    【讨论】:

    • 感谢您的回复!现在发生的事情是我收到超时错误。你有什么想法吗?
    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多