node package manager
Don’t reinvent the wheel. Reuse code within your team. Create a free org »


build status # bencoding for JS (node.js)

This is a small library to encode and decode bencoded (bittorrent) stuff. Bencoding is specified here.

Get & Install

github repository is here

Installable via npm (npm package name is bncode, note spelling!):

npm install bncode


Encoding works as follows:

var benc  = require("bncode"),
    exmp = {}

exmp.bla = "blup" = "bar" = 1
exmp.woah = {}
exmp.woah.arr = []
exmp.str = new Buffer("Buffers work too")

var bencBuffer = benc.encode(exmp)

// d3:bla4:blup3:foo3:bar3:onei1e4:woahd3:arr \
// li1ei2ei3eee3:str16:Buffers work tooe


Decoding will work progressively, e.g. if you're receiving partial bencoded strings on the network:

var benc = require("bncode"),
    buf  = null

decoder = new benc.decoder()
while (buf = receiveData()) {


Or "all in one"

var benc = require("bncode"),
    buf  = getBuffer(),
    dec  = benc.decode(buf)


There are some subtleties concerning bencoded strings. These are decoded as Buffer objects because they are just strings of raw bytes and as such would wreak havoc with multi byte strings in javascript.

The exception to this is strings appearing as keys in bencoded dicts. These are decoded as Javascript Strings, as they should always be strings of (ascii) characters and if they weren't decoded as JS Strings, dict's couldn't be mapped to Javascript objects.

Mapping bencoding to Javascript

 |                |                                   |
 |  Bencoded      |    Javascript                     |
 |  Strings       |    node Buffers, unless they are  |
 |                |    Dictionary keys, in which case |
 |                |    they become Javascript Strings |
 |  Integers      |    Number                         |
 |  Lists         |    Array                          |
 |  Dictionaries  |    Object                         |
 |                |                                   |

Mapping Javascript to bencoding

The code makes a best effort to encode Javascript to bencoding. If you stick to basic types (Arrays, Objects with String keys and basic values, Strings, Buffers and Numbers) you shouldn't encounter suprises. Expect surprises (mainly not being able to round-trip encode/decode) if you encode fancy data-types.


bncode was written by Tim Becker ( I can be reached via email or (preferably) submit a bug to the github repository.


  • Roly Fentanes (fent) for bug reports.
  • Clark Fischer (clarkf)
  • The fine folks at Travis.
  • Patrick Williams
  • Feross Aboukhadijeh