javascript - 如何使用 javascript 命令运行 node.js 文件?

标签 javascript node.js json

我正在尝试制作一款在线游戏。它的节奏不快,所以我只需要一个 json 文件。我对 Node.js 非常陌生,对它了解不多。

我尝试过使用这个:https://stackabuse.com/reading-and-writing-json-files-with-node-js/我了解如何使用命令行读取和写入它。如何从 OnClick 等 JavaScript 事件运行 Node js 文件?

Node js:

//this code is mostly stolen from the site I linked to.
'use strict';

const fs = require('fs');

let newdata = {"newdata": "this is new!"}  
let data = JSON.stringify(newdata);  
fs.writeFileSync('data.json', data);   

json:

{
   "test": "hello world"
}

HTML:

<input type="button" value="Click Me!" onclick="
//run the node js file!!!
">

我不知道如何运行该文件。

最佳答案

我认为在解决这个问题之前,你需要问自己你想要得到什么。

  1. 如果你想创建一个在 REST API 中发送 JSON 文件的服务器,使用 NodeJS 的想法是一个好方法,但是你需要让 Web 服务器运行在后台并在 HTML 代码中使用 $.get 命令获取数据。

  2. 如果你想在本地读取JSON文件,你不需要使用NodeJS(JS将是解决这个问题的好方法)

对于第一个解决方案:

NodeJS 代码:

const data = require('/path/to/json/file/data.json')
var path = require('path');
const express = require('express')
const app = express()

app.get('/data', (req, res) => {
    res.json(data)
})

app.get('/', function(req, res) {
    res.sendFile(path.join('/path/to/index/file/index.html'));
});

app.listen('8080')

HTML 代码:

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <body>
        <button onclick="myFunction()">Test</button>
    </body>
    <script>
        function myFunction(){
            $.get("http://localhost:8080/data",
                function(data) {
                    alert(JSON.stringify(data));
                }
            );
        }
    </script>
</html>

关于javascript - 如何使用 javascript 命令运行 node.js 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56895369/

相关文章:

javascript - ngRepeat 动画不适用于所有元素

javascript - JS FullCalendar V4 右键菜单-选定日期

node.js - 一枪流

node.js - Node js tls1.2 和身份验证

javascript - 在 JavaScript 中读取外部 JSON 文件以填充选择下拉列表

Android请求响应太长

json - Scala Play框架中将json数组转换为模型类的Seq

java - 如何在Struts中使用actionform设置文本框值

javascript - 如何传递多个参数,其中某些参数具有运算符号,如 '+' 或 '&'

node.js - 从谷歌电子表格访问本地nodejs服务器