使用 fs.writeFileSync() JS 从 GitHub Raw link 本地下载图像
Downloading Image locally from GitHub Raw link using fs.writeFileSync() JS
目前正在尝试从 GitHub 本地下载图像。一切似乎都正常,提取通过 200 OK
响应,但是,我不明白如何存储图像本身:
const rawGitLink = "https://raw.githubusercontent.com/cardano-foundation/CIPs/master/CIP-0001/CIP_Flow.png"
const folder = "/Folder"
const imageName = "/Test"
const imageResponse = await axios.get(rawGitLink)
fs.writeFileSync(___dirname + folder + imageName, imageResponse, (err) => {
//Error handling
}
)
必须解决四个问题:
- 对于这种情况,图片名称必须包含 png 格式
- 响应必须采用正确的格式作为图像缓冲区
- 您必须写入响应数据而不是对象本身
__dirname
只需要两个下划线
const rawGitLink = "https://raw.githubusercontent.com/cardano-foundation/CIPs/master/CIP-0001/CIP_Flow.png"
const folder = "/Folder"
const imageName = "/Test.png"
const imageResponse = await axios.get(rawGitLink, { responseType: 'arraybuffer' });
fs.writeFileSync(__dirname + folder + imageName, imageResponse.data)
axios returns一个特殊对象:https://github.com/axios/axios#response-schema
let {data} = await axios.get(...)
await fs.writeFile(filename, data) // you can use fs.promises instead of sync
正如@Leau 所说,您应该在文件名中包含扩展名
另一个建议是使用 path
模块来创建文件名:
filename = path.join(__dirname, "/Folder", "Test.png")
目前正在尝试从 GitHub 本地下载图像。一切似乎都正常,提取通过 200 OK
响应,但是,我不明白如何存储图像本身:
const rawGitLink = "https://raw.githubusercontent.com/cardano-foundation/CIPs/master/CIP-0001/CIP_Flow.png"
const folder = "/Folder"
const imageName = "/Test"
const imageResponse = await axios.get(rawGitLink)
fs.writeFileSync(___dirname + folder + imageName, imageResponse, (err) => {
//Error handling
}
)
必须解决四个问题:
- 对于这种情况,图片名称必须包含 png 格式
- 响应必须采用正确的格式作为图像缓冲区
- 您必须写入响应数据而不是对象本身
__dirname
只需要两个下划线
const rawGitLink = "https://raw.githubusercontent.com/cardano-foundation/CIPs/master/CIP-0001/CIP_Flow.png"
const folder = "/Folder"
const imageName = "/Test.png"
const imageResponse = await axios.get(rawGitLink, { responseType: 'arraybuffer' });
fs.writeFileSync(__dirname + folder + imageName, imageResponse.data)
axios returns一个特殊对象:https://github.com/axios/axios#response-schema
let {data} = await axios.get(...)
await fs.writeFile(filename, data) // you can use fs.promises instead of sync
正如@Leau 所说,您应该在文件名中包含扩展名
另一个建议是使用 path
模块来创建文件名:
filename = path.join(__dirname, "/Folder", "Test.png")