I just started learning Node.js with Express Framework, In my React application user sends an Image in base64
format, to the endpoint /session/start
, I want to store this base64
string and make it to buffer from another endpoint /session/recordFile
, I tried to declare a global variable but there is no positive results :), I have a question, what is an appropriate way to achieve this result using Express.js?
const express = require("express");
const axios = require("axios");
const Twitter = require("twitter");
const serverless = require("serverless-http");
const cors = require("cors");
const path = require("path");
const fs = require("fs");
const oauth = require("oauth");
let GlobalFile;
//start session
router.post("/session/start", function (req, res) {
const body = JSON.parse(req.body)
const file = body.binary
GlobalFile = file
});
router.get("/session/recordFile", function (req, res) {
const buf = Buffer.from(GlobalFile, 'base64')
res.send({mockFile: buf})
});
CodePudding user response:
It's generally a bad idea to assign this to a variable on route-level. If two people call your /start
api, the variable will be overwritten with the data from the second call, before you managed to fetch the first data. This approach will not be scalable
Maybe you can check out this question to store your image in a temporary folder, and fetch it at a later time using the name of the file. If you can make the name of the file variable, you'll be able to do multiple GET
calls, before doing your first POST
without losing any data
CodePudding user response:
You will first need to store the image to disk or save Base64 string to DB or in-memory store like NEdb
To save image to Disk
fs.writeFile("out.png", body, 'base64', function(err) {
console.log(err);
});
Then you can use saved image in GET API
let buff = fs.readFileSync('out.png');
let base64data = buff.toString('base64');