nest入门记之「使用axios下载文件」

1,603 阅读1分钟

前言

本文介绍如何在nest里下载一个文件流到本地。

实现

HTTP模块 httpService => axios

nest内置的httpService是使用axios封装的,所以问题等价为如何使用axios下载文件流

要想下载文件,也就是要接受文件流,而非json或者文本,不要让axios编码响应内容。

查阅axios文档,可以得到

// `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default

// `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default

所以只要我们在请求时将responseType设置为stream即可得到返回文件流。

将流置入写入流管道

	const response= await this.httpService.axiosRef({
            url,
            method: 'GET',
            responseType: 'stream'
       }); 
      //或const response=  await this.httpService.get(url,{responseType: 'stream'});
      const logFileWriter = fs.createWriteStream(filePath);
      response.data.pipe(logFileWriter);