0

I am trying to convert an image into a bufferred array like this format

<Buffer ff d8 ff e2 02 1c 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 02 0c 6c 63 6d 73 02 10 00 00 6d 6e 74 72 52 47 42 20 58 59 5a 20 07 dc 00 01 00 19 ... >

i want to send it to my fs.writefile of node since gives error images when it writes my images to file in base64. Thanks

  • What error do you get and why do you want to encode in base64 ? – TGrif Jan 10 '19 at 09:08
  • i have used the fs.readfile previously with the fs.writefile, they worked perfectly but i had to hardcode the location of the image on the client computer to the fs.readfile, but javascript cant get me the image address location, i cant use fs.readfile but it stores image as buffer so i thought i could do that in JS and pass it to the fswritefile. As for the error the image written in base64 is just blank, my purpose is to just write this images to a file in the website – Akinnifesi Damilola Jan 10 '19 at 09:37

1 Answers1

0

You have to read about Streams and how to use them for processing data.
If your goal is to have array of buffers, you can write something like this:

const fs = require('fs');

const img = '/path/to/image.jpg';

const fileStream = fs.createReadStream(img);

const buffers = [];

fileStream.on('data', chunk => {
  buffers.push(chunk);
})

fileStream.on('end', () => {
  console.log(buffers)
})

But, if you'd like to write file to another location, it's better to pipe() streams.
Like this code:

fs.createReadStream(file).pipe(fs.createWriteStream(destination))

Also, here is amazing tutorial on using streams

Grynets
  • 2,477
  • 1
  • 17
  • 41
  • Thank you sir, looks awesome but before I try I'm at a stop still how do I pass the path to image on client computer to nodejs, that's my major problem now. – Akinnifesi Damilola Jan 10 '19 at 09:56
  • @AkinnifesiDamilola oh, I got it. You need to upload file to server and than save. You have to use multipart/form-data in your client (https://stackoverflow.com/a/4526286/6066986) and then process received file with some npm package, like multer https://github.com/expressjs/multer https://scotch.io/tutorials/express-file-uploads-with-multer – Grynets Jan 10 '19 at 10:36
  • Thank you so much, multer reduced my code drastically, impressive stuff never herd of it till now. Thank you so much – Akinnifesi Damilola Jan 16 '19 at 04:29