Home > Back-end >  How to convert image buffer to file object in NodeJS?
How to convert image buffer to file object in NodeJS?

Time:05-23

Purpose

How do I make a file in the same path in NodeJS in the same form as client request form?

// test.js 
const readFile = fs.readFileSync(filepath, (err, data) => {
if (err) {
    console.log(err)
} else {
    return data
} })
// result : <Buffer 89 50 4e 47 0d 0a 1a 0a ..... >
mysdk(readFile)
// error : it need to file name, size(bytes) , type ...

I want File object like this.

enter image description here

File locate

enter image description here

CodePudding user response:

I guess you are looking for something like this

const process = require('process');
const fs = require('fs-extra');
const express = require('express');

const cwd = process.cwd();
const app = express();
const PORT = 9091;

app.get('/read-file', async(req, res) => {
  const rawFileData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAR8AAACvCAMAAADzNCq AAABCFBMVEX///8zMzNnnmM/hz8sLCx/f39Pm0NSn0RXpkZLlkJZqEZUokVRnkQuLi5NmUNfmltdrkcnJyd4eHhfsUhal1VpaWljtklIkkFVVVXr8uqTk5M/iz3B1b/z PNesEi40Lecv5ocHBxkZGRnvEoYGBg ljeJiYk kzmnxqcTExPJyckiIiL19fWjo6Pl5eVJSUk mjXU4tPY2Ng8PDyxsbEzgjNuomqGsYM9ozHOzs6pqam5ubmZmZmRvI/f6t93qHMAAACRwI6RyIs9py u0anJ4MVZnlF2t2duqWc4kSmyz69UsDV9snak0JqZwpXB3rp1vmCOyH4ghBs0mCozpCMrmR4ifCJMkkoAGmboAAAOHklEQVR4nO2de2OayBrGUawmUSSkJMYoURONGkwiJpHc1Ha33XOa7m7P2Z7tfv9vchgYLsNcGJBWqzz/1DQG4cc7D3N531EQfm5Nbo8vV30O66xDReocT1Z9Fuurw0IuV i8Ga36PNZVgE8up gvqz6RNZXDJ5fTc3erPpW1lMsnl vcPK76ZNZQPp c1Dm8XvXprJ0CfCyj1i8yo0aF8LGMuvC06jNaL4X4WEZ9m/WGAsL45KRh5kK cD455WTVJ7VGIvApvFn1Sa2RMj5sZXzYyviwlfFhK PDVsaHrYwPWxkftjI bGV82Mr4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gw63mdlZ 0WTMkCjaauPBZZhq8AnlGU9WAA k5W2nkeE6oN/j2Y7ucrS8HjLYDsDdqUSdbfxcBr 8YuaZt1NJZjyI3GL4zHgocgdltvFkz3SCnIe6zNgwYNvVNPPT9poZz/8BSlBRCaM/uYQAAAAASUVORK5CYII=';
  var fileData = rawFileData.replace(/^data:image\/\w ;base64,/, "");
  var buffer = Buffer.from(fileData, 'base64');
  const newFileName = 'nodejs.png';
  // now buffer contains the contents of the file we just read
  await fs.writeFile(`./${newFileName}`, buffer, 'utf-8').then( () => {
    res.status(200).sendFile(`${cwd}/${newFileName}`);
  });
});

app.listen(PORT, () => {
  console.log(`server listening on port: ${PORT}`)
});

output

CodePudding user response:

const fs = require('fs');
const path = require('path');

const filePath = path.resolve(__dirname, 'example/sucess.png');
const fileExists = fs.existsSync(filePath);
if (!fileExists) {
    throw new Error(`no such file or directory: ${filePath}`);
}
const contents = fs.readFileSync(filePath, 'utf8');
  • Related