我正在尝试制作一款在线游戏。它的节奏不快,所以我只需要一个 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!!!
">
我不知道如何运行该文件。
最佳答案
我认为在解决这个问题之前,你需要问自己你想要得到什么。
如果你想创建一个在 REST API 中发送 JSON 文件的服务器,使用 NodeJS 的想法是一个好方法,但是你需要让 Web 服务器运行在后台并在 HTML 代码中使用
$.get
命令获取数据。如果你想在本地读取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/