Skip to main content
This recipe migrates usage of the legacy buffer.atob() and buffer.btoa() APIs to the current recommended Buffer-based approaches for base64 encoding and decoding.

What It Does

The codemod transforms:
  • buffer.atob(data)Buffer.from(data, 'base64').toString('binary')
  • buffer.btoa(data)Buffer.from(data, 'binary').toString('base64')

Usage

npx codemod nodejs/buffer-atob-btoa

Examples

Migrating buffer.atob()

Decoding base64-encoded data:
const buffer = require('node:buffer');
const data = 'SGVsbG8gV29ybGQh'; // "Hello World!" in base64
const decodedData = buffer.atob(data);
console.log(decodedData); // Outputs: Hello World!

Migrating buffer.btoa()

Encoding data to base64:
const buffer = require('node:buffer');
const data = 'Hello World!';
const encodedData = buffer.btoa(data);
console.log(encodedData); // Outputs: SGVsbG8gV29ybGQh

Why Migrate?

The buffer.atob() and buffer.btoa() methods were convenience wrappers around Buffer operations. Using Buffer methods directly:
  • Provides more explicit control over encoding
  • Aligns with modern Node.js best practices
  • Reduces dependency on the buffer module import
  • Offers better performance in some scenarios
The Buffer API provides more encoding options beyond ‘base64’ and ‘binary’, including ‘hex’, ‘utf8’, ‘ascii’, and more.

References

Build docs developers (and LLMs) love