Encode and decode base64 strings. Written in TypeScript, published with both ES module and CommonJS builds and type declarations. Requires Node.js 20 or newer.
Usage
Install with npm
npm install libbase64
Require in your script
const libbase64 = require('libbase64');
or import it as an ES module
import libbase64 from 'libbase64';// orimport { encode, decode, wrap, Encoder, Decoder } from 'libbase64';
Encode values
Encode Buffer objects or unicode strings with
libbase64.encode(val) → String
Where
val is a Buffer, an Uint8Array or an unicode string
Example
libbase64.encode('jõgeva');// asO1Z2V2YQ==
Decode values
Decode base64 strings to a Buffer with
libbase64.decode(str) → Buffer
Where
str is a base64 encoded string. Line breaks and other characters outside of the base64 alphabet are ignored. Input made of several separately padded segments (eg. every line padded on its own) is decoded segment by segment
Example
libbase64.decode('asO1Z2V2YQ==').toString();// jõgeva
Wrap encoded values
To enforce soft line breaks on lines longer than selected amount of characters, use wrap
libbase64.wrap(str[, lineLength]) → String
Where
str is a base64 encoded string
lineLength (defaults to 76) is the maximum allowed line length
libbase64 makes it possible to encode and decode streams with libbase64.Encoder and libbase64.Decoder constructors.
Encoder Stream
Create new Encoder Stream with
const encoder = new libbase64.Encoder([options])
Where
options is the optional stream options object
options.lineLength (Number) if you want to use any other line length than the default 76
characters (or set to false to turn the soft wrapping off completely)
options.skipStartBytes (Number) Optional. How many bytes to skip from output (default to 0)
options.limitOutputBytes (Number) Optional. How many bytes to return (defaults to all bytes). The misspelled limitOutbutBytes that earlier versions documented is still accepted
options.startPadding (String) Optional. Fills first line with provided padding string. Usually goes together with skipStartBytes to get line folding correct.
The output is the same as libbase64.wrap(libbase64.encode(input), lineLength), no matter how the input is split into chunks.
Example
The following example script reads in a file, encodes it to base64 and saves the output to a file.