簡體   English   中英

在index.html中使用node.js腳本

[英]Using node.js scripts in index.html

我有一個腳本,用於從reddit抓取數據,稱為scraper.js。 看起來像這樣:

var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');

request("https://www.reddit.com/r/all", function(error, response, body) {
if(error) {
    console.log("Error: " + error);
}
console.log("Status code: " + response.statusCode);

var $ = cheerio.load(body);

$('div#siteTable > div.link').each(function( index ) {
    var title = $(this).find('p.title > a.title').text().trim();
    var time = $(this).find('p.tagline').text().trim();
    var user = $(this).find('a.author').text().trim();


    console.log("Title: " + title);
    console.log("Author: " + user);
    console.log("Time: " + time);
    // possibly wrap this part in <li> tags???
    fs.appendFileSync('reddit.txt', title + '\n');

});
});

這正是我想要在運行時執行的操作:

node script.js

在終端中,但是如何在index.html文件中進行此操作?

您可以同時在客戶端和服務器端使用Node Express。

 const express = require('express') const app = express() app.set('view engine', 'ejs'); app.get('/', (req, res) => res.render('index', { title: 'Express' }); app.listen(3000, () => console.log('Example app listening on port 3000!')) 
 file name use index.ejs <h1>test</h1> <div ><%= title %></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM