nodejs 使用http和fs模块读取网络图片,并写入到本地
写入本地目录的./1.jpg文件中
const http = require("http");
const fs = require('fs')
let url = 'http://www.tucao.one/api.php?op=checkcode&code_len=4&font_size=14&width=446&height=40&font_color=&background='
// 用http的get方法来发送请求
http.get(url, (response) => {
  //data 存储图片数据,是二进制流 
  var data = "";
  // 一定要设置encode,否则即使在pic/downImg/中有1.jpg,也是无法显示的
  response.setEncoding("binary")
  // 当数据到达时会触发data事件
  response.on('data', function (chunk) {
    data += chunk;
  });
  // 当数据接收完毕之后,会触发end事件
  response.on("end", function () {
    //写入文件
    fs.writeFile('./1.jpg', data, 'binary', (err) => {
      if (err) {
        console.log('写入文件错误')
      } else {
        console.log('写入文件成功')
      }
    })
  });
}).on("error", function () {
  console.log('读取错误')
});
要申明encode为binary。
博客园作者:herry菌朋友,看到这里,关注作者的公众号吧,不漏掉更新哦

 
   
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号