From 0d46f9d3310335867267f12ad8e1bea09f6fcafb Mon Sep 17 00:00:00 2001 From: nobody Date: Mon, 26 Oct 2020 23:10:51 +0800 Subject: [PATCH] Refine filepath --- src/utils.ts | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index 25e9045..486cc48 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,11 +1,19 @@ +const sanitize = (str: string) => { + if (typeof str !== 'string') { + return str; + } + + str = str.replace(/"<>#%\{\}\|\\\^~\[\]`;\?:@=&/g, '').replace(/:\/\/|\//g, '-'); + + return Buffer.from(str).toString('utf8'); +}; + export const createFilename = (uri: string, title: string): string => { const extension = 'html'; let filename = `unknown.${extension}`; let url: URL; - try { - url = new URL(decodeURI(uri)); - } catch (_) { + if (!uri || typeof uri != 'string' || uri.length === 0) { return filename; } @@ -13,15 +21,11 @@ export const createFilename = (uri: string, title: string): string => { title = title.replace(/\n|\r|\r\n/gm, ''); } - const sanitize = (str: string) => { - if (typeof str !== 'string') { - return str; - } - - str = str.replace(/"<>#%\{\}\|\\\^~\[\]`;\?:@=&/g, ''); - - return Buffer.from(str).toString('utf8'); - }; + try { + url = new URL(decodeURI(uri)); + } catch (_) { + return sanitize(`${uri.replace(/\./g, '-')}-${title}.${extension}`); + } const hostname = url.hostname .replace(/\./g, '-')