如何运行一个js文件?

How to run a js file?

我正在尝试获取一个博客 (https://www.mrmoneymustache.com) 文章的所有链接,以便将它们编译成 pdf,但我在 javascript 方面完全是个菜鸟。 reddit 上有人告诉我使用这段代码,它应该做我想做的事:

const fs = require('fs');
const EventEmitter = require('events').EventEmitter;
const fetch = require('node-fetch');
const cheerio = require('cheerio');

const e = new EventEmitter();

e.on('fetchPage', link => {
  fetch(link).then(r => r.text()).then(cheerio.load).then($ => {
    const nextLink = $(".next_post a").attr('href');
    if (nextLink === undefined) return; // end on final page
    const postTitle = $(".headline").text();
    const postContent = $(".post_content").html();
    console.log(postTitle);
    fs.writeFileSync(postTitle + ".html", postContent);
    setTimeout(() => e.emit('fetchPage', nextLink), 5000);
  });
});

e.emit('fetchPage', 'https://whatever/post1');

但我真的不明白我应该如何 运行 这个程序.. 请帮忙?

安装Node.js,然后运行这个命令在命令shell:

node yourfile.js

您将必须安装 node and then node-fetch and cheerio using npmjs,节点包管理器。 然后,运行 和

node thenameoftheprogram.js

然而,有许多抓取工具可以在线使用并且学习曲线不那么陡峭。他们可能更适合您的问题。