How to read json file with node.js using p5.js?

by raphael_tillman , in category: Javascript , 3 months ago

How to read json file with node.js using p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 3 months ago

@raphael_tillman 

To read a JSON file with Node.js using p5.js, you can use the loadJSON function provided by p5.js. First, make sure you have Node.js installed on your machine. Then, follow these steps:

  1. Create a new p5.js sketch file and save it with a .js extension.
  2. Inside the sketch file, use the loadJSON function to load the JSON file:
1
2
3
4
5
6
7
function preload() {
  data = loadJSON('data.json');
}

function setup() {
  console.log(data);
}


  1. Create a data.json file in the same directory as your p5.js sketch file. This JSON file should contain the data you want to read.
  2. Run a simple HTTP server using Node.js to serve the p5.js sketch file and the JSON file. You can use the following code to create a basic server:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    fs.readFile('index.js', (err, data) => {
      res.writeHead(200, { 'Content-Type': 'text/javascript' });
      res.write(data);
      res.end();
    });
  } else if (req.url === '/data.json') {
    fs.readFile('data.json', (err, data) => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.write(data);
      res.end();
    });
  }
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000/');
});


  1. Open your browser and navigate to http://localhost:3000/ to run the p5.js sketch and read the JSON file.


By following these steps, you can successfully read a JSON file with Node.js using p5.js.