25

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?

2 Answers 2

49

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

Sign up to request clarification or add additional context in comments.

5 Comments

If you're just now coming to this comment, please know that new Buffer has been deprecated in replace of Buffer.from(...). You can read more about this here: nodejs.org/api/…
@ChasenBettinger thanks for the heads up -- updated to show the proper usage of Buffer
Its hard to find answers for File Object, tsk tsk
If anyone here is a frontend developer, confused with backend operations, and was looking for File Object -> Buffer, while uploading image files on server, know that on server files should be processed with library like Busboy and will become FileStreams, not File Objects. So you need to convert FileStream to Buffer - that's probably what you're looking for. I answered on this topic here: stackoverflow.com/a/77429654/10489004
Does not work in TypeScript. Getting: Argument of type File is not assignable to parameter of type WithImplicitCoercion<string> | { [Symbol.toPrimitive](hint: 'string'): string; }
14

In 2024 this is what I'm doing – which makes typescript happy.

First create an ArrayBuffer from the file, then pass the ArrayBuffer to Buffer.from like so

const arrayBuffer = await file.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.