web建站教程
     
  1. 首页
  2. 前端UI组件库
  3. AI项目和框架
  4. AIGC工具
  5. 百度echarts
  6. 地图大全
  7. 前端知识
  8. 更多
    vuejs
    js入门
    php入门
    mysql
    wordpress
    织梦cms
    帝国cms
    git教程
    IT知识
    模板大全
    休息站
    AI应用

如何利用nodejs实现http文件下载功能

1172 ℃

nodejs语法如何实现http文件下载,下面web建站小编给大家简单介绍一下!

具体代码如下:

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');
});

如何利用nodejs做一个手机号注册功能

nodejs简简单单做一个文件夹上传功能

标签: http文件下载 nodejs功能

上面是“如何利用nodejs实现http文件下载功能”的全面内容,想了解更多关于 nodejs 内容,请继续关注web建站教程。

当前网址:https://ipkd.cn/webs_4685.html

声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

当前位置: 首页 > nodejs
Trae:新一代免费的AI编程工具

呱呱工具箱

一款免费的在线小工具,无需下载,打开即可使用!呱呱工具箱

在线育儿补贴计算器

快来看看你到底可以领到多少补贴!生活小工具
上一篇:
下一篇:
x 打工人ai神器