我正在尝试使用node.js编写脚本来下载图像.这是我到目前为止:
var maxLength = 10 // 10mb
var download = function(uri, callback) {
http.request(uri)
.on('response', function(res) {
if (res.headers['content-length'] > maxLength*1024*1024) {
callback(new Error('Image too large.'))
} else if (!~[200, 304].indexOf(res.statusCode)) {
callback(new Error('Received an invalid status code.'))
} else if (!res.headers['content-type'].match(/image/)) {
callback(new Error('Not an image.'))
} else {
var body = ''
res.setEncoding('binary')
res
.on('error', function(err) {
callback(err)
})
.on('data', function(chunk) {
body += chunk
})
.on('end', function() {
// What about Windows?!
var path = '/tmp/' + …Run Code Online (Sandbox Code Playgroud) 我正在尝试利用节点请求模块,但文档并不是那么好.如果我向有效资源发出请求并将其传递给Writable Stream,那么一切正常.但是,如果我向无效对象发出请求,则仍会创建可写流.例如,请使用以下代码段:
var x = request("http://localhost:3000/foo.jpg");
var st = fs.createWriteStream("foo.jpg");
x.pipe(st);
Run Code Online (Sandbox Code Playgroud)
如果服务器上存在foo.jpg资源,则数据将通过管道传输到流,并在服务器上创建文件.但是,如果服务器上不存在foo.jpg ,则仍会创建空白容器文件.似乎没有任何错误事件或任何可用于确定请求是否返回404的内容.我尝试过以下内容:
var x = request("http://localhost:3000/foo.jpg", function(err, response, body) {
if(response.statusCode === 200) {
// Success
var st = fs.createWriteStream("foo.jpg");
x.pipe(st);
}
});
Run Code Online (Sandbox Code Playgroud)
并且:
request("http://localhost:3000/foo.jpg", function(err, response, body) {
if(response.statusCode === 200) {
// Success
var x = response.request;
var st = fs.createWriteStream("foo.jpg");
x.pipe(st);
}
});
Run Code Online (Sandbox Code Playgroud)
无济于事.这个想法非常简单; 我只想将URL标识的文件复制到本地服务器.如果请求无效(404等),请不要管道文件; 如果请求有效,则管道文件.有什么建议?