Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lirantal/fbf76f7ab3a87de8a2630a711bc946d5 to your computer and use it in GitHub Desktop.
Save lirantal/fbf76f7ab3a87de8a2630a711bc946d5 to your computer and use it in GitHub Desktop.
ChatGPT-generated Fastify Node.js app for file uploads
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