Starter code to set up a p5.js project to route HTTP GET requests using Node.js in the Getting Started with Node.js tutorial. It this tutorial, you set up the enviernment for GET requests to read file names from a local folder called songs
and parses them into a JSON array.
Ensure that you have p5.js installed on your machine or are using the p5.vscode extension in VS Code. See Setting Up Your Enviernment for more details on how to download and create p5.js projects on your local device using VS Code.
This starter code contains a directory called melody_app_starter-main
with 2 folders and 2 files. - The public
folder holds all the main files to run a p5.js project as seen on the p5.js Web Editor.
- The
songs
folder holds JSON files that we will retrieve. - The
README.md
file is the file with these instructions - The
server.js
file contains the Node.js and Express.js functions that create the routing enviernment for HTTP requests.
//Import express
let express = require('express');
// Create the Express app
let app = express();
// Set the port used for server traffic.
let port = 3000;
// Middleware to serve static files from 'public' directory
app.use(express.static('public'));
//Run server at port
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
The code in the server.js
file creates the enviernment to enable HTTP requests in p5.js using Node.js and Express.js.
- The
require
function is a built-in Node.js function used to import modules. Here the Express.js module is imported with the argument'express'
, and stored in the variable calledexpress
. - The
express()
function creates an instance of an Express.js application object. Here the application is stored in the variable calledapp
. We useapp
to call methods for routing and configuring HTTP requests. - A global variable called
port
stores a value of 3000 and is used inapp.listen()
at the bottom. - The
app.use(express.static('public'))
mounts the middleware to access thepublic
folder from your current directory. This enables the p5.js project to run in the browser using the main filesindex.html
,style.css
andscript.js
files. - The code that begins with
app.listen(port, () => {...
starts the server and makes it listen for incoming requests on the specifiedport
. After the server starts this message appears in the terminal:Server running at http://localhost:3000
The server is running and can be accessed at the specific url: http://localhost:3000
- Complete the Getting Started with Node.js tutorial
- Complete the Melody App tutorial
Please reach out to [email protected] if you encounter any errors in code or documentation