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。

posted @ 2021-10-27 19:21  herry菌  阅读(2818)  评论(0编辑  收藏  举报