Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert file to buffer in node.js?

I am writing a sails.js app. I am writing an API to accept a file and encrypt it.

var file = req.body('myFile');
var fileBuffer = convertToBuffer(file);

How do I convert a file to buffer?

like image 646
Jaseem Abbas Avatar asked Oct 29 '15 14:10

Jaseem Abbas


People also ask

What is a file buffer Nodejs?

Node. js buffers are objects that store arbitary binary data. The most common reason for running into buffers is reading files using Node. js: const fs = require('fs'); const buf = fs.

Which method is used for writing to buffer in Node JS?

The write() method writes the specified string into a buffer, at the specified position.

What is file buffer?

A file buffer is the temporary image of the file that you can edit. You can edit the file buffer without affecting the original file, until you save it using the Save command. The File > Save command writes the file buffer contents back over the original file. This is the only time the original file is changed.


1 Answers

That looks like you've got a string which represents the body of your file.

You just have to make a new buffer with it.

var fileBuffer = Buffer.from(file)

If your encoding is NOT utf8 you can specify an alternate encoding as a second optional argument.

var fileBuffer = Buffer.from(file, 'base64')

If the file is actually on disk, this is even easier, since, by default, the fs.readFile operation returns a buffer.

fs.readFile(file, function(err, buffer){})

If you're in a real old version of node Buffer.from doesn't exist and you have to use a very memory-unsafe new constructor. Please consider upgrading your node instance to support Buffer.from

like image 152
tkone Avatar answered Oct 07 '22 08:10

tkone