乐闻世界logo
搜索文章和话题

How to download a file with Node.js (without using third-party libraries)?

1个答案

1

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:

javascript
const 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:

  1. Import necessary modules: We need http, fs, and path modules to complete the task.
  2. Create HTTP server: Using http.createServer, we create a simple server to handle HTTP requests.
  3. Specify file path: Use path.join to construct the absolute path of the file to download.
  4. Read file information: Use fs.stat to obtain file information, primarily for setting the Content-Length header.
  5. Set response headers: We send a 200 OK status and headers indicating this is a file for download, such as Content-Type and Content-Disposition.
  6. Use streams to read the file: Create a read stream with fs.createReadStream to read the file content and pipe it directly into the response object.
  7. Error handling: Add error handling to notify the client if errors occur during file stream reading.
  8. 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.

2024年6月29日 12:07 回复

你的答案