node.js webtorrent collect all files by magnet link

1.7k Views Asked by At

I have not used node.js before.
Have a .txt file with list of magnet links. Want to write a json file with list of all files contained in these links.

var WebTorrent = require('webtorrent');
var fs = require('fs');
var client = new WebTorrent();
var array = fs.readFileSync('yop.txt').toString().split("\n");
i = 0;
while (i < array.length) {
//console.log(array[i]);
var magnetURI = array[i];
n = 0;
client.add(magnetURI, function (torrent) {
    torrent.files.forEach(function (file) {
        //console.log( file.name)
        jsonString = JSON.stringify({'book': file.name});
        fs.appendFile("data.json", jsonString, function (err) {
            if (err) {console.log(err);} else { n++ }
        });
        if (n == torrent.files.length) {i++ }
    })
})

}

when run gives the following error
Sorry for such a terrible code.

1

There are 1 best solutions below

1
On
var WebTorrent = require('webtorrent')
var fs = require('fs')
var stream = fs.createWriteStream("2.txt");
var client = new WebTorrent()
var array = fs.readFileSync('yop.txt').toString().split("\n");

i = 0;

function parseMagnet (uri){

    var magnetURI = uri[i]
    console.log(magnetURI)
    client.add(magnetURI, function (torrent) {
      torrent.files.forEach(function (file) {
        writeStr = (uri[i]+ '\n'+ file.name+ '\n');
        stream.write(writeStr);
       console.log(file.name)       
      });
       console.log('Done !') 
       console.log(i)
       i += 1          
       parseMagnet(array);
       client.remove(magnetURI);
    })

}

parseMagnet(array)