如何在浏览器中使用webtorrent?

时间:2014-11-19 18:54:42

标签: javascript html browserify webtorrent

我在https://github.com/feross/webtorrent#usage中显示的示例遇到了一些问题 我正在尝试在浏览器中使用代码。所以我首先创建一个名为app.js的文件

app.js

var WebTorrent = require('webtorrent')
var concat = require('concat-stream')

var client = new WebTorrent()
console.log('Hi there');
client.download('magnet:?xt=urn:btih:XXXXXXXX', function (torrent) {
  // Got torrent metadata!
  console.log('Torrent info hash:', torrent.infoHash)

  torrent.files.forEach(function (file) {
    // Get the file data as a Buffer (Uint8Array typed array)
    file.createReadStream().pipe(concat(function (buf) {

      // Append a link to download the file
      var a = document.createElement('a')
      a.download = file.name
      a.href = URL.createObjectURL(new Blob([ buf ]))
      a.textContent = 'download ' + file.name
      document.body.appendChild(a)
    }))
  })
})

然后我输入命令browserify app.js > bundle.js,这样可以使代码适用于浏览器。我创建了另一个名为index.html的文件:

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test</title>
    <script src="bundle.js"></script>
</head>

<body id="home">

    <h1>test</h1>


</body>
</html>

从控制台我只能看到“你好”。似乎client.download()函数不起作用。为什么会这样?我是浏览器的新手,我使用的命令有什么问题吗?

1 个答案:

答案 0 :(得分:7)

WebTorrent只能下载明确播种到WebTorrent网络的种子。 Torrent客户需要支持WebRTC与Web浏览器对等。目前,没有客户支持它,但您可以使用http://instant.io开始播种新的torrent并尝试使用应用程序中的WebTorrent库下载它。通过设置`localStorage.debug ='*'来启用http://instant.io上的调试日志,以获取torrent的信息哈希值。

您还可以在此处了解更多信息: