-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[fetch] Move download image function into package
- Loading branch information
Showing
3 changed files
with
34 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import { statSync, writeFileSync } from "node:fs" | ||
import * as path from "node:path" | ||
|
||
export const downloadImage = async (dir: string, url: string, meta: { blockId: string; lastEditedTime: Date }) => { | ||
const fileUrl = new URL(url) | ||
const originalFileName = fileUrl.pathname.substring(fileUrl.pathname.lastIndexOf("/") + 1) | ||
const originalFileExtension = originalFileName.split(".").pop() | ||
const newFileName = path.join(dir, `${meta.blockId}.${originalFileExtension}`) | ||
|
||
let savedLastEditedTime: Date | null = null | ||
try { | ||
const stat = statSync(newFileName) | ||
savedLastEditedTime = stat.mtime | ||
} catch (error) { | ||
if (error instanceof Error && "code" in error && error.code === "ENOENT") { | ||
console.debug(`${newFileName} not found`) | ||
} else { | ||
console.warn(`${newFileName}: ${error}`) | ||
} | ||
} | ||
// Avoid download the file again and again | ||
if (savedLastEditedTime === null || meta.lastEditedTime > savedLastEditedTime) { | ||
const resp = await fetch(fileUrl) | ||
const blob = await resp.blob() | ||
writeFileSync(newFileName, new DataView(await blob.arrayBuffer())) | ||
console.info(`downloaded image ${newFileName} of block ${meta.blockId}`) | ||
} | ||
|
||
return newFileName | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
export * from "./fetch" | ||
export * from "./image" | ||
export * from "./properties" |