How to convert file to buffer in node.js?

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

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

How to convert a file to a buffer?

+4
source share
1 answer

It looks like you have a line representing the body of your file.

You just need to make a new buffer with it.

var fileBuffer = new Buffer(file)

If your encoding is not utf8, you can specify an alternate encoding of the second optional argument.

var fileBuffer = new Buffer(file, 'base64')

If the file is on disk, this is even easier, because by default the operation fs.readFilereturns a buffer.

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

Source: https://habr.com/ru/post/1613666/


All Articles