Created
September 12, 2023 11:32
-
-
Save lirantal/fbf76f7ab3a87de8a2630a711bc946d5 to your computer and use it in GitHub Desktop.
ChatGPT-generated Fastify Node.js app for file uploads
This file contains hidden or 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
const fastify = require("fastify")(); | |
const fs = require("fs"); | |
const path = require("path"); | |
// Set the directory where uploaded files will be saved | |
const UPLOADS_DIRECTORY = "uploads/"; | |
// Create the uploads directory if it doesn't exist | |
if (!fs.existsSync(UPLOADS_DIRECTORY)) { | |
fs.mkdirSync(UPLOADS_DIRECTORY); | |
} | |
// Define a route handler for file uploads | |
fastify.post("/api/uploads", async (request, reply) => { | |
// Check if the request contains a file in the 'file' field | |
if (!request.isMultipart() || !request.files.file) { | |
return reply.status(400).send("No file uploaded."); | |
} | |
// Get the uploaded file object | |
const uploadedFile = request.files.file; | |
// Set the file path where the file will be saved | |
const fileName = uploadedFile.name; | |
const filePath = path.join(UPLOADS_DIRECTORY, fileName); | |
// Save the file to disk | |
const writeStream = fs.createWriteStream(filePath); | |
writeStream.on("finish", () => { | |
reply.send("File uploaded successfully!"); | |
}); | |
uploadedFile.pipe(writeStream); | |
}); | |
// Start the server | |
fastify.listen(3000, (err) => { | |
if (err) { | |
console.error(err); | |
process.exit(1); | |
} | |
console.log("Server listening on port 3000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment