NW JS – 从URL下载并保存文件

我最近开始使用NW.JS开发桌面应用程序,我需要从URL( http://someurl.org/file.zip )下载文件,我设法保存文件,但似乎损坏或格式错误,我可以'打开zip或解压缩。

我正在使用jQuery从Node.JS下载文件和'fs'模块来保存它。

这是ajax请求:

module.exports.download = function (jQuery, url) { return jQuery.ajax({ url : url, timeout : 1000000 }); }; 

其余的是:

 $('#btnUpdateClient') .click(function () { ClientDownload .download($, addresses.CLIENT_URL) .complete(function (xhr, status) { console.log(xhr); fs.writeFile('./files/staClient.zip', xhr.responseText, function (err) { if(err) { alert('error!'); console.log(err); } else { alert('file Saved!'); } }); }); }); 

有些东西显然缺less,而.zip文件是3.8 MB,但是当我fs.writeFile()文件结束了7.3 MB

我对NW.JS相当陌生,有什么build议吗?

没关系,我只是意识到我甚至不需要使用jQuery,我只是简单地使用了NodeJS:

 $('#btnUpdateClient') .click(function () { var file = fs.createWriteStream('./files/staClient.zip'); var request = http.get(addresses.CLIENT_URL, function (response) { response.pipe(file); }); }); 

如果下载进度对您很重要,请使用以下命令:

 var http = require('http'); var fs = require('fs'); var req = http.get('http://someurl.org/file.zip', function (res) { var fileSize = res.headers['content-length']; res.setEncoding('binary'); var a = ""; res.on('data', function (chunk) { a += chunk; document.getElementById('percent').innerHTML = Math.round(100*a.length/fileSize) + ""; }); res.on('end', function() { fs.writeFile('D:\\file.zip', a, 'binary', function (err) { if (err) throw err; console.log('finished'); }); }); });