0

I am trying to make an online game. It is not fast-paced, so I only need a json file. I am very new to node.js and don't really know much about it.

I have tried using this: https://stackabuse.com/reading-and-writing-json-files-with-node-js/ and I understand how to read and write to it with the command line. How can I run a node js file from a javascript event like OnClick?

The 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);   

The json:

{
   "test": "hello world"
}

The html:

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

I have no idea what I can do to run the file.

2
  • 1
    nodeJS files are hosted in a web server, you can only access these using http methods, get, post.. Commented Jul 5, 2019 at 1:02
  • You can't run a node.js file by clicking on a button. Commented Jul 5, 2019 at 4:56

1 Answer 1

1

I think before you solve this problem you need to ask yourself what you tried to get.

  1. If you want to make a server which sends in REST API the JSON file, the idea to using NodeJS is a good way, but you need to let the web server to run in the background and use $.get commands at the HTML code to get the data.

  2. If you want to read the JSON file locally you didn't need to use NodeJS (JS will be the good way to solve this)

For the first solution:

NodeJS code:

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 code:

<!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>
Sign up to request clarification or add additional context in comments.

2 Comments

I definitely need to make a server. What I want is to have a server online and type something like: server.player1.points and be able to read & write to it in real time. I currently have a domain, do I need to purchase anything else?
@Ben I add my solution to your problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.