【问题标题】:How can I read and write into another file using javascript on html website?如何在 html 网站上使用 javascript 读取和写入另一个文件?
【发布时间】:2020-08-28 23:26:01
【问题描述】:

我正在尝试制作一个简单的网站,您可以在其中单击按钮并对其进行计数,并且它还应该告诉您单击的频率。我尝试使用 fs ,因为我使用 Discord 机器人做了类似的事情并且效果很好。但在网络上,它只是没有。 它看起来像这样:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script>
      var fs = require('fs');
      var counting = JSON.parse(fs.readFileSync('./Storage/count.json', 'utf8'));
      var button = document.getElementById("button");

      button.onclick = function() {

          counting[count]++;

          fs.writeFile('./Storage/count.json', JSON.stringify(counting), (err) => {
              if (err) console.error(err);
          });
      };

    </script>
  </head>
  <body>
    <div style="text-align: center">
      <button id="button">Increment</button>
    </div>
  </body>
</html>

(如果有一些明显的错误,我很抱歉,但我对这种东西比较陌生)

当然还有 JSON

{"count":0}

【问题讨论】:

  • 您希望文件以给定路径写入访问者磁盘或网络服务器上的什么位置?
  • 错误1:var fs = require('fs'); ...浏览器不是nodejs。错误 2:网页无权访问客户端文件系统 - 你能想象如果有的话你能做什么!!!

标签: javascript html web fs


【解决方案1】:

很遗憾,您不能在浏览器中使用fs,因为它是一个节点模块。 参考:https://nodejs.org/api/fs.html

一种可能的方法是让您获取现有节点/fs 代码并将其移动到服务器端。然后,您只需要为您的网站开发端点即可访问。

否则,您可以尝试使用localStorage 之类的方法将计数存储到客户端的浏览器中。

 localStorage.setItem('count', 0);

更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多