11import fs from "node:fs" ;
22import path from "node:path" ;
33import sanitizeFilename from "sanitize-filename" ;
4+
45import { getCode } from "./getCode.js" ;
5- import { getPosterAsync } from "./utils/getPosterAsync.js" ;
66import { searchAsync } from "./searchAsync.js" ;
7+ import { getPosterAsync } from "./utils/getPosterAsync.js" ;
78
89/** @param {string } filePath */
910export async function parseAsync ( filePath ) {
@@ -13,8 +14,7 @@ export async function parseAsync(filePath) {
1314 if ( metadata ) {
1415 const newName = sanitizeFilename ( metadata . title ) . slice ( 0 , 120 ) . trim ( ) ;
1516 const newPath = path . join ( dir , newName + ext ) ;
16- const didFail = await renameAsync ( filePath , newPath ) ;
17- if ( ! didFail ) {
17+ if ( await renameAsync ( filePath , newPath ) ) {
1818 await downloadAsync ( dir , metadata . imageUrl , newName ) ;
1919 return "OK" ;
2020 } else {
@@ -26,16 +26,16 @@ export async function parseAsync(filePath) {
2626}
2727
2828/**
29- * @param {string } dir
29+ * @param {string } directoryPath
3030 * @param {URL } imageUrl
3131 * @param {string } name
3232 */
33- async function downloadAsync ( dir , imageUrl , name ) {
33+ async function downloadAsync ( directoryPath , imageUrl , name ) {
3434 const response = await fetch ( imageUrl ) ;
35- const fanart = await response . arrayBuffer ( ) . then ( Buffer . from ) ;
35+ const fanart = await response . arrayBuffer ( ) . then ( Buffer . from . bind ( Buffer ) ) ;
3636 const poster = await getPosterAsync ( fanart ) ;
37- await fs . promises . writeFile ( path . join ( dir , `${ name } -fanart.jpg` ) , fanart ) ;
38- await fs . promises . writeFile ( path . join ( dir , `${ name } .jpg` ) , poster ) ;
37+ await writeImageAsync ( path . join ( directoryPath , `${ name } -fanart.jpg` ) , fanart ) ;
38+ await writeImageAsync ( path . join ( directoryPath , `${ name } .jpg` ) , poster ) ;
3939}
4040
4141/**
@@ -49,10 +49,19 @@ async function renameAsync(oldPath, newPath) {
4949 . then ( ( ) => true )
5050 . catch ( ( ) => false ) ;
5151 if ( exists ) {
52- return true ;
52+ return false ;
5353 } else {
5454 await fs . promises . rename ( oldPath , newPath ) ;
5555 }
5656 }
57- return false ;
57+ return true ;
58+ }
59+
60+ /**
61+ * @param {string } filePath
62+ * @param {Buffer } buffer
63+ */
64+ async function writeImageAsync ( filePath , buffer ) {
65+ await fs . promises . writeFile ( `${ filePath } .tmp` , buffer ) ;
66+ await fs . promises . rename ( `${ filePath } .tmp` , filePath ) ;
5867}
0 commit comments