【问题标题】:Printing Random Values from a JSON File In nodejs从 nodejs 中的 JSON 文件打印随机值
【发布时间】:2021-07-21 13:19:34
【问题描述】:

我有一个巨大的 json 文件,其中包含 75000 个引号。 https://s41.aconvert.com/convert/p3r68-cdx67/uy0lx-j9b81.json。我想选择一个随机报价并将其显示在一个 html 文件中。我用的是nodejs,谁能告诉我怎么做?

【问题讨论】:

标签: javascript html css node.js json


【解决方案1】:

您需要在本地下载文件,因为该站点不允许外部请求。

const fs = require("fs");

function randomIndex(size) {
    return Math.floor(Math.random() * size);
}

const quotes = JSON.parse(fs.readFileSync("quotes.json", { encoding: "utf-8", flag: "r" }));

const selectedQuote = quotes[randomIndex(quotes.length)];

document.getElementById("quote").innerHTML = `"${selectedQuote.QUOTE}" - ${selectedQuote.AUTHOR} (genre: ${selectedQuote.GENRE})`;

<span id="quote">Here is where your quote will be</span>

【讨论】:

  • 我应该使用ejs来链接html和nodejs文件吗?
  • AFAIK Node 不允许使用 HTML,但您需要解决这个问题,我的回答就是一个例子。我认为你不能在浏览器中运行 Node。
  • 您可以使用名为 ejs 的模块链接 html 和 nodejs。我指的是那个。谢谢大家的帮助。
猜你喜欢
  • 2021-11-06
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
相关资源
最近更新 更多