I have the following:
const fileAsString = fs.readFileSync('speech.mp3', { encoding: 'utf-8' })
const encryptedString = encrypt(fileAsString)
const decryptedString = decrypt(encryptedString)
console.log(fileAsString === decryptedString) // this returns true
fs.writeFileSync('speech_copy.mp3', decryptedString, { encoding: 'utf-8' })
speech_copy.mp3 is created but it’s no longer playable because I have messed up its encoding.
What am I doing wrong in the process? The only reason I’m originally reading the file using { encoding: 'utf-8' } is so that I may encrypt it and then decrypt it again. Should I use a different encoding when I write it back as a new file?
Advertisement
Answer
Using a base64 representation of the binary data is usually a better way:
const fs = require('fs');
// binary -> base64
const fileAsString = fs.readFileSync('speech.mp3').toString('base64');
const encryptedString = encrypt(fileAsString);
const decryptedString = decrypt(encryptedString);
// base64 -> binary
fs.writeFileSync('speech_copy.mp3', Buffer.from(decryptedString , 'base64'));