javascript - nodejs下载解压后的文件
PHPz
PHPz 2017-04-10 17:57:49
[JavaScript讨论组]

nodejs怎么实现下载一个zip,直接解压后保存到指定目录?

PHPz
PHPz

学习是最好的投资!

全部回复(2)
PHPz

server.js

const express = require("express");
const app = express();
const path = require('path');
const fs = require('fs');

app.get('/download', function(req, res){
  const zipFilePath = path.join(__dirname, '../public/zipFile.zip'); // your file path
  fs.createReadStream(zipFilePath).pipe(res)
})
app.listen(3000, function(err) {
  if(err) console.error(err);
  console.log("OK");
});

client.js

const http = require("http");
const path = require('path');
const fs = require('fs');
const decompress = require('decompress');

const options = {
    hostname: 'localhost',
    port: 3000,
    path: '/download',
    method: 'GET'
};

var req = http.request(options, function(res) {
    const zipFilePath = path.join(__dirname, './zipFileDownload.zip')
    const writeStream = fs.createWriteStream(zipFilePath)
    res.on('data', function (chunk) {
        writeStream.write(chunk)
    });
    res.on('end', function (chunk) {
        writeStream.end(chunk)
    });
    writeStream.on('finish', function() {
      const decompressFolderPath = path.join(__dirname, 'contents') // your decompress folder
      decompress(zipFilePath, decompressFolderPath).then(files => console.log('done'))
    })
});

req.on('error', function(e) {
    console.error('problem with request: ' + e.message);
});

// write data to request body
// req.write(JSON.stringify(body)); // if you have query data or body

req.end();
  • 解压的库有很多,我这里只是列举一个给你,adm-zip等,可以自己找找,如果还有问题,留言吧!写的太仓促了,待优化哈!

PHP中文网

res.download(path [, filename] [, fn])

res.download('/report-12345.pdf');

res.download('/report-12345.pdf', 'report.pdf');

res.download('/report-12345.pdf', 'report.pdf', function(err){
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
});

http://expressjs.com/en/4x/ap...

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号