在JavaScript中将docx文件编码为base64

在JavaScript中将docx文件编码为base64,javascript,node.js,base64,Javascript,Node.js,Base64,我正在本地下载一个docx文件,并希望将其编码为base64,但似乎编码docx文件不起作用。我在.txt和图像中尝试过这个方法,它确实返回了base64字符串。我是否必须使用库或其他方法来编码docx文件 async function encodeBase64(path) { let buff = fs.readFileSync(path); let base64data = buff.toString('base64'); return base64data; } htt

我正在本地下载一个docx文件,并希望将其编码为base64,但似乎编码docx文件不起作用。我在.txt和图像中尝试过这个方法,它确实返回了base64字符串。我是否必须使用库或其他方法来编码docx文件

async function encodeBase64(path) {
   let buff = fs.readFileSync(path);
   let base64data = buff.toString('base64');
   return base64data;
}

https.get(result['@microsoft.graph.downloadUrl'], function(response) {
        const file = encodeBase64(__dirname + "/temp/template.docx");
})
这将导致一个空字符串

编辑:

const file = encodeBase64(__dirname + "/temp/template.docx");
file.then(function(result) {
     console.log(result)
     return res.send(result);  
}).catch(function(error) {
     console.log(error)
})

使用图像和.txt文件,它成功地将结果记录在控制台中。当我尝试使用docx文件执行此操作时,它返回一个空字符串。我绝对肯定它选择的是docx文件,而且里面也充满了内容。

我发现您没有正确使用async wait

在这一行:

const file = encodeBase64(__dirname + "/temp/template.docx");
ecvodeBase64()是异步函数,返回一个承诺。什么样的承诺返回要么进入
.then()
回调函数,要么需要使用wait来检索值

要纠正上述情况,必须执行以下操作:

https.get(result['@microsoft.graph.downloadUrl'], function(response) {
    encodeBase64(__dirname + "/temp/template.docx")
    .then( file => {
        // use file here
    });
});


你是如何得出结论认为它不受支持的?我是说,你有什么错误或意外行为?你可以用:@FedericoklezCulloca道歉,也许我应该用另一个词来形容它。@Stuart为什么?要打开文件并将其内容转换为base64?真的吗?是的-你可以使用MS office js库…抱歉,我没有添加其余的代码。我确实有一个.then函数,在我调用该函数之后(否则NodeJS不会编译应用程序)。我已经编辑了我的代码。我也使用了“等待”,但它也不起作用。我认为要么转换docx文件太大,要么根本无法处理docx文件,只能处理txt/images之类的文件。您可能需要在nodejs中使用Buffer和一些编码检查Buffer类。
https.get(result['@microsoft.graph.downloadUrl'], async function(response) {
    const file = await encodeBase64(__dirname + "/temp/template.docx");
})