Search code examples
node.jsencodingbase64decodeucs2

How to convert ucs2 encoded input to base64 on node.js server


I have a from that uploads an image to a node.js server, and I'd like to handle the incoming image data and convert it to base64.

I'm able to write the file out on the server using the following method:

fs.writeFile('filename.ext', req.files[0].buffer, { encoding: 'ucs2' }, (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

But would like to do something like

let b64 = fs.readFileSync(req.files[0].buffer, 'ucs2');
console.log(b64); // Outputs string of base-64 text.

I'm currently getting an error with this method:

[ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes

Is this achievable with node.js?

What methods should I consider?


Solution

  • Here is your solution:

    let b64 = fs.readFileSync('the-file-you-want-to-read.here').toString('base64');
    console.log(b64);