I want to store docx or pdf locally inside a folder of my node.js project. Those documents are encoded as Base64 strings but they have specific media type. For this reason when I try to write a file in usual ways, as shown below, the result is something of unreadable.
const express = require("express");
const router = express.Router();
const fs = require('fs');
router.post("/evaluate", function(req, res) {
var oResume = req.body.resume;
var sMimeType = oResume.mimeType;
var sFileExtension = oResume.fileExtension;
var sBase64 = oResume.content.replace(/(\r\n|\n|\r)/gm, "");
fs.writeFile("cvs/out." sFileExtension, sBase64, 'base64', function(err) {
console.log(err);
});
res.status(200).send("OK");
});
How can I store a document which maintain the right format?
CodePudding user response:
I've solved with this solution:
const express = require("express");
const atob = require("atob");
const router = express.Router();
const fs = require('fs');
router.post("/evaluate", function(req, res) {
var oResume = req.body.resume;
var sMimeType = oResume.mimeType;
var sFileExtension = oResume.fileExtension;
var sBase64 = oResume.content.replace(/(\r\n|\n|\r)/gm, "");
var sBinaryString = atob(sBase64);
var len = sBinaryString.length;
var aBytes = new Uint8Array(len);
for (var i=0; i<len; i ) {
aBytes[i] = sBinaryString.charCodeAt(i);
}
var blob = Buffer.from(aBytes.buffer);
fs.writeFile("cvs/out." sFileExtension, blob, function(err) {
console.log(err);
});
res.status(200).send("OK");
});
module.exports = router;