我正在尝试创建一个文件下载器作为后台服务,但是当一个大文件被调度时,它首先被放入内存中,然后在下载结束时将文件写入磁盘.
考虑到我可能同时下载了大量文件,如何将文件逐渐写入磁盘保存内存?
这是我正在使用的代码:
var sys = require("sys"),
http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs"),
events = require("events");
var downloadfile = "http://nodejs.org/dist/node-v0.2.6.tar.gz";
var host = url.parse(downloadfile).hostname
var filename = url.parse(downloadfile).pathname.split("/").pop()
var theurl = http.createClient(80, host);
var requestUrl = downloadfile;
sys.puts("Downloading file: " + filename);
sys.puts("Before download request");
var request = theurl.request('GET', requestUrl, {"host": host});
request.end();
var dlprogress = 0;
setInterval(function () {
sys.puts("Download progress: " + dlprogress + " bytes");
}, 1000);
request.addListener('response', function (response) { …Run Code Online (Sandbox Code Playgroud) 我在node.js上创建了一个函数来启动文件下载但是我想创建一个规则,其中函数在下载数据之前检查文件大小.
我得到了响应标题并检查了大小,但我不知道如何通过传输实际数据/正文来取消所有内容.也许有一种方法只能首先传输标题,如果符合我的规则,我可以触发另一个请求进行下载.
这是我的代码片段:
request.on('response', function(response) {
var filesize = response.headers['content-length'];
console.log("File size " + filename + ": " + filesize + " bytes.");
response.pause();
if (filesize >= 50000) {
// WHAT TO PUT HERE TO CANCEL THE DOWNLOAD?
console.log("Download cancelled. File too big.");
} else {
response.resume();
}
//Create file and write the data chunks to it
Run Code Online (Sandbox Code Playgroud)
谢谢.