One basic approach to implementing file download in Node.js is to use the built-in http module to create a server and the fs (File System) module to read the file content and send it as a response to the client. Here is a simple example demonstrating how to set up a server in Node.js that provides file downloads:
javascriptconst http = require('http'); const fs = require('fs'); const path = require('path'); // Create HTTP server const server = http.createServer((req, res) => { // Specify the file path to download const filePath = path.join(__dirname, 'example.txt'); // Read file information fs.stat(filePath, (err, stat) => { if (err) { console.error('Error getting file stats.'); res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Server error.'); return; } // Set response headers to indicate this is a file for download res.writeHead(200, { 'Content-Type': 'application/octet-stream', // or set to the actual file type 'Content-Disposition': `attachment; filename="${path.basename(filePath)}"`, 'Content-Length': stat.size, }); // Use streams to read the file and write to the response const readStream = fs.createReadStream(filePath); readStream.pipe(res); // Handle stream errors readStream.on('error', (error) => { console.error('Error reading file stream.'); res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Server error.'); }); }); }); const port = 3000; server.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
The following is a step-by-step explanation:
- Import necessary modules: We need
http,fs, andpathmodules to complete the task. - Create HTTP server: Using
http.createServer, we create a simple server to handle HTTP requests. - Specify file path: Use
path.jointo construct the absolute path of the file to download. - Read file information: Use
fs.statto obtain file information, primarily for setting theContent-Lengthheader. - Set response headers: We send a
200 OKstatus and headers indicating this is a file for download, such asContent-TypeandContent-Disposition. - Use streams to read the file: Create a read stream with
fs.createReadStreamto read the file content and pipe it directly into the response object. - Error handling: Add error handling to notify the client if errors occur during file stream reading.
- Listen on port: Finally, the server listens on the specified port, waiting for client connections and requests.
Using the above server code, when a client (e.g., a browser) accesses the server, it will automatically start downloading the example.txt file. This method is suitable for small to medium-sized files because it processes file data through streams and avoids loading the entire file content into memory. For large file downloads, this method already considers memory efficiency. However, if you need to implement features like resumable downloads or other advanced functionalities, you may need to use additional libraries or implement more complex logic.