Writing image to local server

前端 未结 6 1189
孤街浪徒
孤街浪徒 2020-11-28 19:38

Update

The accepted answer was good for last year but today I would use the package everyone else uses: https://github.com/mikeal/request


6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 19:46

    How about this?

    var http = require('http'), 
    fs = require('fs'), 
    options;
    
    options = {
        host: 'www.google.com' , 
        port: 80,
        path: '/images/logos/ps_logo2.png'
    }
    
    var request = http.get(options, function(res){
    
    //var imagedata = ''
    //res.setEncoding('binary')
    
    var chunks = [];
    
    res.on('data', function(chunk){
    
        //imagedata += chunk
        chunks.push(chunk)
    
    })
    
    res.on('end', function(){
    
        //fs.writeFile('logo.png', imagedata, 'binary', function(err){
    
        var buffer = Buffer.concat(chunks)
        fs.writeFile('logo.png', buffer, function(err){
            if (err) throw err
            console.log('File saved.')
        })
    
    })
    

提交回复
热议问题