Node.js axios文件下载并将线索存储在损坏的文件中(编码问题)?
我使用Node.js axios文件下载并将线索存储在损坏的文件中(编码问题)?,node.js,axios,fs,Node.js,Axios,Fs,我使用axios下载了一个典型的JPG文件,并将其存储在磁盘上,如下所示: // Just create axios instance that does not care about HTTPS certificate validity // since I need to download from an untrusted internal service. // Included for completeness. Do not borrow this bit unless you k
axios
下载了一个典型的JPG文件,并将其存储在磁盘上,如下所示:
// Just create axios instance that does not care about HTTPS certificate validity
// since I need to download from an untrusted internal service.
// Included for completeness. Do not borrow this bit unless you know what you are doing.
const axiosInstance = axios.create({
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
});
// Download file
fileData = await axiosInstance.get(imageUrl, {
responseType: 'arraybuffer',
});
console.log(`Dowloaded OK, size ${fileData.data.length} bytes`));
// Dump file to disk
await fs.writeFile(`${filename}`, fileData.data, (err) => {}
});
我注意到,虽然console.log报告正确的字节数和fileData.data
在调试器中看起来正常,但记录的文件的字节数是原来的两倍,并且自然会损坏。似乎非英语字母变成了2字节而不是1字节。我怀疑这与编码有关
我怎样才能更正此错误,以便正确记录文件?我想问题在于如何调用
writeFile
,我建议您尝试一下
fs.writeFile(`${filename}`,{encoding:'binary'},fileData.data,(err)=>{})
//或
fs.writeFile(`${filename}`,Buffer.from(fileData.data),(err)=>{})
然而,正确的方法是在数据传入时使用流,并直接写入磁盘
通过这种方式,程序将使用更少的内存,并且具有时间效率。程序不会等待所有数据下载并保存在RAM中,然后尝试写入磁盘,而是“动态”写入磁盘
工作示例:
const axios=require('axios'))
const path=require('路径')
常量fs=require('fs')
const target\u path=path.resolve(\u dirname,'some\u random\u filename'))
const input=fs.createWriteStream(目标路径“二进制”)
axios
.get('https://via.placeholder.com/150', {
响应类型:'stream'
})
.then(res=>res.data.pipe(输入))
.catch(err=>console.error(err))
参考资料:
writeFile
,我建议您尝试一下
fs.writeFile(`${filename}`,{encoding:'binary'},fileData.data,(err)=>{})
//或
fs.writeFile(`${filename}`,Buffer.from(fileData.data),(err)=>{})
然而,正确的方法是在数据传入时使用流,并直接写入磁盘
通过这种方式,程序将使用更少的内存,并且具有时间效率。程序不会等待所有数据下载并保存在RAM中,然后尝试写入磁盘,而是“动态”写入磁盘
工作示例:
const axios=require('axios'))
const path=require('路径')
常量fs=require('fs')
const target\u path=path.resolve(\u dirname,'some\u random\u filename'))
const input=fs.createWriteStream(目标路径“二进制”)
axios
.get('https://via.placeholder.com/150', {
响应类型:'stream'
})
.then(res=>res.data.pipe(输入))
.catch(err=>console.error(err))
参考资料:
responseType:'blob'
或responseType:'binary'
下载的文件有任何想法,请建议您对如何保存使用responseType:'blob'
或responseType:'binary'
下载的文件有何想法