每当网页加载时,我如何 运行 一个 NodeJS 脚本?

How can I run a NodeJS script whenever a webpage loads?

让我尽我所能解释一下我的项目。我正在使用 webpack 和 deck.gl 制作一个显示地图数据的 JavaScript app/website。地图数据来自 JSON 文件,但是 JSON 数据只有在我 运行 我编写的 NodeJS 网络抓取程序时才会附加。

两件事,我如何自动化这个脚本,以便在网站 (index.html) 首次加载时它 运行s,我将如何托管这样的网站在我本地主机之外的平台上?

提前致谢。


修复/解决方案:

How would can I automate this script so it runs whenever the website (index.html) is loaded for the first time

我最终通过 Express 创建了一个网络服务器并将我的代码作为函数调用(scrape.js 文件如下所示)

const express = require('express');
const app = express();
const scrape = require('./scrape.js');

app.get('/', (req, res) => {
    scrape();
})

app.listen(3000);

and how would I go about hosting a website like this on a platform outside of my localhost

几乎每个主要的托管平台都允许您托管 Node 应用程序,所以我决定使用 AWS - specifically AWS EC2 Instance

how can I automate this script so it runs whenever the website (index.html) is loaded for the first time

  1. 创建网络服务器(例如使用 Express.js)
  2. 重写脚本,使其可以作为函数调用,然后在访问您主页的路由时调用它

例如

const yourscript = require("./yourscript.js");

app.get('/', (req, res) => {
    yourscript();
    res.render('index')
})

(并非详尽示例,请阅读 Express.js 文档)

并确保通过从网络服务器请求加载网页(例如 http://localhost:3000/ 而不是直接从文件系统访问文件)。

how would I go about hosting a website like this on a platform outside of my localhost?

寻找专为 运行 Node.js 应用程序设计的托管服务,并按照他们的说明进行操作。