Create a nodejs code with the follow instruction: 1. open port at 3000, 2. add path for…
- User
Create a nodejs code with the follow instruction: 1. open port at 3000, 2. add path for "/upload" which will be used to upload files into the server, every file send to that path will be saved as "/files/{uuid}" 3. in the end of the code display the url for server with network ip and add an comment for how to upload a file using curl
- Assistant
// Import required modules const express = require('express'); const multer = require('multer'); const { v4: uuidv4 } = require('uuid'); const path = require('path'); const os = require('os'); const fs = require('fs'); // Initialize the Express application const app = express(); // Define the directory to store uploaded files const filesDir = path.join(__dirname, 'files'); // Create the files directory if it doesn't exist if (!fs.existsSync(filesDir)) { fs.mkdirSync(filesDir); } // Configure Multer storage settings const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, filesDir); // Save files in the /files directory }, filename: function (req, file, cb) { const uniqueName = uuidv4() + path.extname(file.originalname); // Generate a unique filename using UUID cb(null, uniqueName); } }); // Initialize Multer with the defined storage settings const upload = multer({ storage: storage }); // Define the /upload route to handle file uploads app.post('/upload', upload.single('file'), (req, res) => { if (!req.file) { return res.status(400).send('No file uploaded.'); } // Construct the URL to access the uploaded file const fileUrl = `${req.protocol}://${req.headers.host}/files/${req.file.filename}`; res.send(`File uploaded successfully: ${fileUrl}`); }); // Serve the uploaded files statically from the /files directory app.use('/files', express.static(filesDir)); // Function to retrieve the local network IP address function getLocalIP() { const interfaces = os.networkInterfaces(); for (let iface of Object.values(interfaces)) { for (let addr of iface) { if (addr.family === 'IPv4' && !addr.internal) { return addr.address; } } } return 'localhost'; } // Start the server on port 3000 app.listen(3000, () => { const localIP = getLocalIP(); console.log(`Server is running at http://${localIP}:3000`); }); /* To upload a file using curl, run the following command in your terminal: curl -F "file=@/path/to/your/file" http://<server_ip>:3000/upload Replace `/path/to/your/file` with the path to the file you want to upload and `<server_ip>` with your server's IP address. */Explanation of the Code:
-
Dependencies:
- express: Web framework for Node.js.
- multer: Middleware for handling
multipart/form-data, which is primarily used for uploading files. - uuid: Generates unique identifiers (UUIDs) to ensure each uploaded file has a unique name.
- path, os, fs: Built-in Node.js modules for handling file paths, operating system-related utility methods, and file system operations respectively.
-
File Storage Setup:
- The code ensures that a directory named
filesexists in the root of your project. If it doesn't, the directory is created. This directory is where all uploaded files will be stored.
- The code ensures that a directory named
-
Multer Configuration:
- Destination: Specifies that uploaded files should be saved in the
/filesdirectory. - Filename: Generates a unique filename for each uploaded file by combining a UUID with the original file's extension.
- Destination: Specifies that uploaded files should be saved in the
-
Upload Route (
/upload):- Accepts
POSTrequests with a file field namedfile. - Uses Multer to handle the file upload.
- After a successful upload, it responds with the URL where the uploaded file can be accessed.
- Accepts
-
Static File Serving:
- The
/filesroute serves the uploaded files, allowing them to be accessed via a URL.
- The
-
Server Initialization:
- The server listens on port
3000. - Upon starting, it retrieves and logs the server's local network IP address, making it easy to access the server from other devices on the same network.
- The server listens on port
-
cURL Upload Instruction:
- A comment at the end provides a sample
curlcommand to upload files to the server. Replace the placeholders with your actual file path and server IP address.
- A comment at the end provides a sample
Usage Instructions:
-
Install Dependencies: Ensure you have Node.js installed. Then, install the required packages by running:
npm install express multer uuid -
Run the Server: Save the above code in a file, say
server.js, and run:node server.jsThis will start the server on port
3000and display the server's URL with the network IP. -
Upload a File Using cURL: Open a terminal and execute:
curl -F "file=@/path/to/your/file" http://<server_ip>:3000/uploadReplace
/path/to/your/filewith the path to the file you want to upload and<server_ip>with the IP address displayed by the server. -
Access Uploaded Files: After a successful upload, you'll receive a URL in the response. Open that URL in your browser to access the uploaded file.
This setup provides a simple and efficient way to upload and serve files using Node.js.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.