This gist contains the server code code described in the article Run a Node.js® Express Server on your Raspberry Pi®.
Created
January 29, 2022 19:53
-
-
Save jmp-12/290fc65c4eebcfc07905c4e6c35ae590 to your computer and use it in GitHub Desktop.
Run a Node.js® Express Server on your Raspberry Pi®
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (c) 2020 - 2022 Persanix LLC. All rights reserved. | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
// Built-in libraries | |
const fs = require("fs"); | |
const os = require("os"); | |
// Third-party libraries | |
const express = require("express"); | |
const homeDirectory = os.homedir(); | |
const app = express(); | |
// Respond to GET requests to the route "/files" with a JSON file list or an error | |
// Note: app.get() corresponds to the HTTP verb GET, similarly app.post() corresponds to POST | |
app.get("/files", (request, response) => { | |
// fs.readdir() is an asynchronous function takes a callback (a function to invoke when the operation is complete) | |
fs.readdir(homeDirectory, (error, files) => { | |
// Something weird happened, respond with the error message | |
// Note: NEVER respond with a stacktrace in a production application. Log the error and move on. | |
// Users seeing a stacktrace is a security vulnerability at worst and poor UX at best | |
if (error) { | |
return response.status(500).send(error.message); | |
} | |
// There must not be an error, respond with the file list as JSON | |
response.json(files); | |
}); | |
}); | |
// Start the server on port 5000 and call console.log() when the server is started (another callback function) | |
app.listen(5000, () => console.log("Server is up!")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment