简体   繁体   中英

Using node.js scripts in index.html

I have a script that is used to scrape data off of reddit called scraper.js. It looks like this:

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');

});
});

This does exactly what I want it to do when run:

node script.js

in my terminal, but how do I go about getting this to happen in my index.html file?

you can use Node Express for both client side and server side together.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM