Node.js的那些坑(一)—— 图片下载有时为0字节

Node.js的那些坑(一)—— 图片下载有时为0字节

问题:node.js下载图片一直是打开为空的状态

  • 错误代码
async getImage(imageUrl) {
    const imageInfo = this.getImageInfo(imageUrl);
    const imagePath = path.join(__dirname, `../static/image/${imageInfo.name}`);
    await request.get(imageUrl).pip(fs.createWriteStream(imagePath))
  },
const rp = = require('request-promise');
async getImage(imageUrl) {
    const imageInfo = this.getImageInfo(imageUrl);
    const imagePath = path.join(__dirname, `../static/image/${imageInfo.name}`);
    await  rp.get(imageUrl).pipe(fs.createWriteStream(imagePath));
  },
  • 优化代码
async getImage(imageUrl) {
    const imageInfo = this.getImageInfo(imageUrl);
    const imagePath = path.join(__dirname, `../static/image/${imageInfo.name}`);
    // const isexit = fs.statSync(imagePath);
    return new Promise(resolve => {
      request({
        url: imageUrl,
        encoding:null
      }, (err, response, body) => {
        fs.writeFileSync(
          imagePath, 
          body,
          {
            encoding:'binary'
          }
        )
        resolve()
       })
    })
  },
  • 原因:
1 Star2 Stars3 Stars4 Stars5 Stars (2 打了分, 平均分: 5.00)
Loading...

发表评论

邮箱地址不会被公开。 必填项已用*标注