Home >Web Front-end >Front-end Q&A >nodejs implements http file download

nodejs implements http file download

王林
王林Original
2023-05-27 17:48:381315browse

Node.js is an open source, cross-platform JavaScript runtime environment that allows JavaScript code to run on the server. In Node.js, we can easily create a simple http server through the http module, and realize the file download function by reading local files. This article will introduce how to use Node.js to implement http file download.

  1. Create http server

Using the http module of Node.js, you can create an http server very easily. The code is as follows:

const http = require('http');

const server = http.createServer((req, res) => {
  console.log('Request received');
});

server.listen(3000, () => {
  console.log('Server started on port 3000');
});

This code creates Created an http server that listens for requests on port 3000. When the server receives any request, 'Request received' is output on the console.

  1. Handling http requests

To implement the file download function, we need to obtain the requested URL in the request handler and determine the file to be downloaded based on the requested URL. document. The code is as follows:

const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  console.log('Request received');

  const fileUrl = req.url.slice(1);
  const filePath = `./${fileUrl}`;

  fs.stat(filePath, (err, stats) => {
    if (err) {
      res.statusCode = 404;
      res.end('File not found');
      return;
    }

    fs.readFile(filePath, (err, data) => {
      if (err) {
        res.statusCode = 500;
        res.end('Error reading file');
        return;
      }

      res.setHeader('Content-Disposition', `attachment; filename=${fileUrl}`);
      res.setHeader('Content-Type', 'application/octet-stream');
      res.setHeader('Content-Length', stats.size);
      res.end(data);
    });
  });
});

server.listen(3000, () => {
  console.log('Server started on port 3000');
});

In this code, we get the file name from the requested URL and determine the file path based on the file name. Next, we use the stat method of the fs module to check whether the file exists. If the file does not exist, we send a 404 response to the client and return a 'File not found' message. If the file exists but an error occurs while reading the file contents, we send a 500 response to the client and return an 'Error reading file' message. If everything is fine, we set the response headers and send the file contents to the client.

  1. Test the download function

We can enter 'http://localhost:3000/file.txt' in the browser, where file.txt is to be downloaded file name. If the file exists, the server will download it.

Summary

In this article, we introduced how to implement http file downloading through Node.js. We created an http server to handle client requests and read local files through the fs module and send them to the client as response content. This example provides a very simple way to provide file download functionality to the client, but in practice, we may want to consider implementing more practical download management, such as file size limits, download speed limits, and verification of whether the file is a legal file. wait.

The above is the detailed content of nodejs implements http file download. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn