Node.js 将接口获取的文件流变成文件内容 - 使用 fs 模块
申请的头顶和内容已经进行了 SEO 优化和重写。
Node.js 将接口获取的文件流变成文件内容
使用 fs 模块可以将接口获得的文件流转换成文件。
首先、您需要通过 HTTP 请求获得文件流。可以使用 http 模块或者类似 axios 的第三方库来发送 HTTP 请求并获得文件流。这里以使用 axios 库为例:
const axios = require('axios');
const fs = require('fs');
axios({
method: 'get',
url: 'http://example.com/file',
responseType: 'stream' // 设置备应类型为流
})
.then(response => {
// 创建可写流
const fileStream = fs.createWriteStream('path/to/save/file.ext');
// 将文件流管道到可写流中
response.data.pipe(fileStream);
// 当文件流写入完成时、关闭可写流
fileStream.on('finish', () => {
fileStream.close();
console.log('文件存储完成');
});
})
.catch(error => {
console.log('请求出错', error);
});
在上述的代码中、我们使用 axios 发送 HTTP GET 请求、并设置备应类型为流。然后、我们创建一个可写流、将文件流管道到可写流中、最后存储文件并关闭可写流。
请注意、 response.data 是一个可读流、可以使用 pipe 方法将其管道到可写流中。在文件流写入完成后、我们关闭可写流。
您需要将 url 替换成您要请求的接口地址、将 path/to/save/file.ext 替换成您要存储文件的路径和文件名称。
如果您不想使用第三方库、可以使用 http 模块来发送 HTTP 请求、然后使用 fs 模块来处理文件流。以下是使用 http 模块的示例代码:
const http = require('http');
const fs = require('fs');
const fileStream = fs.createWriteStream('path/to/save/file.ext');
http.get('http://example.com/file', response => {
response.pipe(fileStream);
fileStream.on('finish', () => {
fileStream.close();
console.log('文件存储完成');
});
})
.on('error', error => {
console.log('请求出错', error);
});
这里的代码与上述使用 axios 的代码类似、只是使用了 http.get 方法发送 HTTP GET 请求并获得文件流。
原文地址: https://www.cveoy.top/t/topic/pwIe 著作权归作者所有。请勿转载和采集!