From 2e3e46df0ec083e2689c2bc1095a2c4734f71e3c Mon Sep 17 00:00:00 2001 From: Eric Seigers Date: Fri, 9 Oct 2020 12:17:37 +0900 Subject: [PATCH] add save to disk option --- README.md | 1 + lib/ssi.js | 13 ++++++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9822bf9..d0da12d 100644 --- a/README.md +++ b/README.md @@ -59,3 +59,4 @@ module: { | defaultCharset | string | utf-8 | force the file reader to convert the file content into a specific charset | | quietError | boolean | false | if the file cannot be found on local or online replace it with an error message or not | | onFileMatch | function | null | callback on each SSI line match with 3 parameters : filePath<string>, fileContent<string>, isLocal<boolean>.
If you return a string it will override and replace the content | +| saveToDisk | boolean | false | saves files fetched online to disk (if not present) | diff --git a/lib/ssi.js b/lib/ssi.js index f5cbd39..b9dea74 100644 --- a/lib/ssi.js +++ b/lib/ssi.js @@ -2,6 +2,7 @@ const request = require('then-request'); const iconv = require('iconv-lite'); const chardet = require('chardet'); const fs = require('fs'); +const path = require('path'); /** * take HTLM string scan it to find ssi include string @@ -24,7 +25,8 @@ const SSI = function (param) { disableLocalScan: false, includesMatcher: //, onFileMatch: () => null, - } + saveToDisk: false, + }; const options = { ...defaultOptions, ...param, @@ -73,6 +75,15 @@ const SSI = function (param) { content = iconv.decode(res.body, charset); } + const target = `${options.localPath}${location}`; + + if (options.saveToDisk && !fs.existsSync(target)) { + const targetDir = path.dirname(target); + + fs.mkdirSync(targetDir, { recursive: true }); + fs.writeFileSync(target, content); + } + const modifiedContent = options.onFileMatch(url, content, false); return modifiedContent || content; } catch(e) {