【发布时间】:2018-01-27 11:28:05
【问题描述】:
我正在尝试使用 node.js 中的程序下载 phar(PHP 存档)。经过一些测试,我发现从浏览器和 node.js 下载的文件不一样。
我尝试了一些方法:
“二进制”编码
“utf8”编码
这些都不起作用。
有人知道我应该使用哪种编码来下载 phar 吗?
我的代码:
exports.download = function(urlStr, dest, cb) { // urlStr is the url link of the phar, dest is the destination file, and cb is the callback.
var options = {
headers: {
"User-Agent": "PSM (Pocketmine Server Manager, https://psm.mcpe.fun) User Requester"
}
}
var data = "";
var url = new URL(urlStr);
options.hostname = url.hostname;
options.path = url.pathname;
var request = http.get(options, function(response) {
// check if response is success
if (response.statusCode == 302 || response.statusCode == 301) {
exports.download(response.headers["location"], dest, cb);
return;
}
response.on("data", function(chunk) {
data += chunk.toString("binary");
})
response.on('end', function() {
fs.writeFileSync(dest, data, "binary");
cb();
});
}).on('error', function(err) { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
if (cb) cb(err.message);
});
};
使用的 Phar(有效):https://psm.mcpe.fun/download/PSMCore/1.1.phar
【问题讨论】: