node.jstorrentwebtorrent

downloading torrent from peers in nodejs


I use this piece of code to download torrent:

var torrentStream = require('torrent-stream');

var engine = torrentStream('magnet:?xt=urn:btih:44A91362AFFF802F9058993B109C544ACC6B4813');

engine.on('ready', function(e) {
    engine.files.forEach(function(file) {
        console.log('filename:', file.name);
        var stream = file.createReadStream();
        // stream is readable stream to containing the file content
    });
});

This torrent is correctly downloaded by utorrent, but it doesn't work in nodejs (nothing happens). Any ideas why? May be p2p network was not bootstrapped? How can I do this?

Thanx


Solution

  • Of corse there happens nothing, because you dont do anything with the stream in the example. If you want to save it to a file you can create a write stream:

    var writeStream = fs.createWriteStream('file2.txt')
    stream.pipe(writeStream)
    

    or you can use the stream with events:

    var data = ''
    stream.on('data', chunk => {
      data += chunk
    })
    stream.on('end', () => {
      console.log(data)
    })