Skip to content

Instantly share code, notes, and snippets.

@teidesu
Created June 22, 2021 13:11
Show Gist options
  • Save teidesu/5e23c5f2af0b6b435ccbe47b805e6f82 to your computer and use it in GitHub Desktop.
Save teidesu/5e23c5f2af0b6b435ccbe47b805e6f82 to your computer and use it in GitHub Desktop.
Simple NodeJS function to convert .torrent files to magnet URIs
// This file is licensed under LGPLv3
// (c) teidesu 2020
const qs = require('querystring')
const crypto = require('crypto')
// https://gist.github.com/teidesu/a1eadf71ffd88166415e2ea8b94d3f3b
const bencode = require('./bencode')
function convert (file) {
const data = bencode.decode(f)
const infoHash = crypto.createHash('sha1').update(encode(data.info)).digest('hex')
let params = {
xt: `urn:btih:${infoHash}`,
tr: []
}
if ('length' in data.info) {
params.xl = data.info.length
}
if ('name' in data.info) {
params.dn = data.info.name.toString('utf-8')
}
if ('announce' in data) {
params.tr.push(data.announce.toString('utf-8'))
}
if ('announce-list' in data && Array.isArray(data['announce-list'])) {
params.tr.push(...data['announce-list'].map(ann => ann.toString('utf-8')))
}
return 'magnet:?' + qs.stringify(params)
}
// usage:
console.log(convert(require('fs').readFileSync('lorem-ipsum.torrent')))
@negu63
Copy link

negu63 commented Nov 30, 2022

I tested using Bittorrent and it worked fine. I'm not sure what's wrong. 😥

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment