nodejs下载解压后的文件

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

阅读 5.7k
2 个回答

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等,可以自己找找,如果还有问题,留言吧!写的太仓促了,待优化哈!

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...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题