使用fs和http模块下载Node.js的zip文件不工作

Downloading a zip file with Node.js using fs and http module not working

本文关键字:zip 文件 工作 js Node fs http 模块 下载 使用      更新时间:2023-09-26

我使用以下代码下载zip文件。如果您将URL放入浏览器中,您将看到它开始下载。但是当我使用Node下载压缩文件时,输出的test.zip文件包含如下内容:

<head><title>Document Moved</title></head>
<body><h1>Object Moved</h1>This document may be found <a HREF="http://patentscdn.reedtech.com/ipg150804-zip/ipg150804.zip?sv=2014-02-14&amp;sr=b&amp;sig=u1W37AFnH9DAcqc7k4tDABaV14eSlchN8fJJ1%2FOkWEo%3D&amp;st=2015-08-04T04%3A00%3A00Z&amp;se=9999-12-31T05%3A00%3A00Z&amp;sp=r">here</a></body>
下面是Node.js代码:
var http = require('http');
var fs = require('fs');
var url = 'http://patents.reedtech.com/downloads/GrantRedBookText/2015/ipg150804.zip';
http.get(url, function(response) {
    response.on('data', function(data) {
        fs.appendFileSync('test.zip', data);
    });
    response.on('end', function() {
        console.log('hello');
    });
});

有一个HTTP重定向,您可以执行以下操作

var http = require('follow-redirects').http;

这将使http遵循重定向。我建议你使用请求库。

检查如何在Node.js中遵循HTTP重定向?查看详细信息