Back to articles
3 Node.js Bugs That Silently Corrupt Your Binary Data

3 Node.js Bugs That Silently Corrupt Your Binary Data

via Dev.to WebdevElle

Binary data in Node.js looks easy until it isn't. I spent a combined 6 hours debugging three bugs that all had the same root cause: treating binary data like strings. If you're calling external APIs that return audio, images, or video — read this before you ship. Bug #1: String concatenation destroys audio files This looks fine: const chunks = [] res . on ( ' data ' , chunk => { chunks . push ( chunk . toString ()) }) res . on ( ' end ' , () => { const audio = chunks . join ( '' ) fs . writeFileSync ( ' output.mp3 ' , audio ) }) The file saves. It has the right size. But it won't play. Why: .toString() defaults to UTF-8 encoding. Binary bytes that aren't valid UTF-8 get replaced with � (U+FFFD). Your audio file is now full of replacement characters where real data used to be. Fix: const chunks = [] res . on ( ' data ' , chunk => chunks . push ( chunk )) res . on ( ' end ' , () => { const audio = Buffer . concat ( chunks ) fs . writeFileSync ( ' output.mp3 ' , audio ) }) Keep everything

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
2 views

Related Articles