[英]How can I execute a console function but from the browser in Node.JS?
我正在嘗試執行此 function 但在帶有 Node.JS 的終端中
var WebTorrent = require('webtorrent')
var client = new WebTorrent()
var magnetURI = 'magnet: ...'
client.add(magnetURI, { path: '/path/to/folder' }, function (torrent) {
torrent.on('done', function () {
console.log('torrent download finished')
})
})
我的意思是,例如,創建一個<button>
標簽,當被點擊時,之前的 function 將在 nodejs 控制台中執行,而不是在瀏覽器控制台中。
額外:我正在執行這兩個文件:
應用程序.js
let http = require('http');
let fs = require('fs');
let handleRequest = (request, response) => {
response.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('./index.html', null, function (error, data) {
if (error) {
response.writeHead(404);
respone.write('Whoops! File not found!');
} else {
response.write(data);
}
response.end();
});
};
http.createServer(handleRequest).listen(8000);
和
index.html 包含<button>
標簽但什么也不做。
客戶端(瀏覽器)和服務器是兩個不同的實體,當客戶端是瀏覽器時,唯一的通信方式是通過HTTP協議,簡單來說就是使用internet。
現在瀏覽器只了解它自己的 javascript,更准確地說是 ECMA 而不是 nodejs。 所以下面的代碼無法在瀏覽器中執行
var WebTorrent = require('webtorrent')
var client = new WebTorrent()
因此,我假設它在您的機器上運行,因此console.log
將打印到您的終端。
要在瀏覽器上運行它,我假設您必須以不同的方式對其進行編碼,要么您必須使用browserify
並分析客戶端腳本,要么僅在客戶端使用以下libaray編寫代碼:
<script src="webtorrent.min.js"></script>
有關更多詳細信息,請參閱https://github.com/webtorrent/webtorrent/blob/master/docs/get-started.md上的完整 web 頁面示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.