@ctrl/torrent-file
v4.5.0
Published
Parse a torrent file (name, hash, files, pieces)
Readme
torrent-file 
Parse a torrent file and read encoded data.
Supports BitTorrent v1 (BEP-3), v2 (BEP-52), and hybrid torrent files.
This project is based on parse-torrent and node-bencode to parse the data of a torrent file. This library implements its own bencode encoder and decoder that does not use Buffer making it easier to use in browser or non node environments.
demo: https://torrent-file.pages.dev
Install
npm install @ctrl/torrent-fileAPI
info
The content of the metainfo file. Includes a version field ('v1', 'v2', or 'hybrid').
import fs from 'fs';
import { info } from '@ctrl/torrent-file';
const torrentInfo = info(fs.readFileSync('myfile'));
console.log({ torrentInfo });files
Data about the files described in the torrent file, includes hashes of the pieces. For v2/hybrid torrents, files include piecesRoot and the result includes pieceLayers. pieces is undefined for v2-only torrents.
import fs from 'fs';
import { files } from '@ctrl/torrent-file';
const torrentFiles = files(fs.readFileSync('myfile'));
console.log({ torrentFiles });hash
SHA-1 of torrent file info. This hash is commonly used by torrent clients as the ID of the torrent.
import fs from 'fs';
import { hash } from '@ctrl/torrent-file';
const torrentHash = hash(fs.readFileSync('myfile'));
console.log({ torrentHash });hashes
Returns both v1 (SHA-1) and v2 (SHA-256) info hashes along with the detected torrent version. infoHashV2 is only present for v2 and hybrid torrents.
import fs from 'fs';
import { hashes } from '@ctrl/torrent-file';
const h = hashes(fs.readFileSync('myfile'));
console.log(h.version); // 'v1', 'v2', or 'hybrid'
console.log(h.infoHash); // SHA-1 (always present)
console.log(h.infoHashV2); // SHA-256 (v2/hybrid only)Encode
Convert a parsed torrent object back into a .torrent file buffer.
import fs from 'fs';
import { toTorrentFile } from '@ctrl/torrent-file';
// Minimal example: create a .torrent buffer from fields
const buf = toTorrentFile({
info: {
// Required info fields
'piece length': 16384,
pieces: new Uint8Array(/* 20-byte SHA1 hashes concatenated */),
name: 'example.txt',
length: 12345,
},
// Optional fields
announce: ['udp://tracker.publicbt.com:80/announce'],
urlList: ['https://example.com/example.txt'],
private: false,
created: new Date(),
createdBy: 'my-app/1.0.0',
comment: 'Generated by @ctrl/torrent-file',
});
fs.writeFileSync('example.torrent', buf);Demo
Run a local demo UI to drop a .torrent file and view parsed output:
pnpm install
pnpm demo:watchTo build the demo for static hosting:
pnpm demo:buildSee Also
parse-torrent - torrent parsing based very heavily off this package
node-bencode - bencoder built into this project heavily based off this package
