diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b1f9d59..21dbe1a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ - widgets: circular value feedback issues - editor: `ctrl + e` not working when hitm multiple times without releasing `ctrl` +- custom module + - add optional `errorCallback` argument to`loadJSON` and `saveJSON` + - misc - add linux rpm packages diff --git a/resources/docs/docs/custom-module/custom-module.md b/resources/docs/docs/custom-module/custom-module.md index b3988bc9..f728e29e 100644 --- a/resources/docs/docs/custom-module/custom-module.md +++ b/resources/docs/docs/custom-module/custom-module.md @@ -96,16 +96,24 @@ Returns the server's http addresses. ---- -#### `loadJSON(path)` +#### `loadJSON(path, errorCallback)` Loads a json file (path is relative to the custom module location) +- `path`: `string`, path to file (any extension allowed, but the content must be valid JSON) +- `errorCallback` (optional): `function`, called with the error as argument if the file can't be loaded + + ---- -#### `saveJSON(path, object)` +#### `saveJSON(path, data, errorCallback)` Saves an object/array to a json file (path is relative to the custom module location) +- `path`: `string`, path to file (any extension allowed) +- `data`: `object`, `array` or any value that can be encoded to JSON +- `errorCallback` (optional): `function`, called with the error as argument if the file can't be loaded + ---- #### `require(path)` diff --git a/src/server/custom-module.js b/src/server/custom-module.js index 20bf6310..b70ebfbe 100644 --- a/src/server/custom-module.js +++ b/src/server/custom-module.js @@ -33,24 +33,32 @@ class CustomModule { require: this.require.bind(this), } : { ...context, - loadJSON: (url)=>{ + loadJSON: (url, errorCallback)=>{ try { url = path.resolve(path.dirname(this.filename), url) var content = fs.readFileSync(url, 'utf8') if (content[0] === '\ufeff') content = content.slice(1) // remove BOM return JSON.parse(content) } catch(e) { - console.error('(ERROR) could not load json file from ' + url) - console.error(e.message) + if (typeof(errorCallback) === 'function') { + errorCallback(e) + } else { + console.error('(ERROR) could not load json file from ' + url) + console.error(e.message) + } } }, - saveJSON: (url, data)=>{ + saveJSON: (url, data, errorCallback)=>{ url = path.resolve(path.dirname(this.filename), url) try { return fs.writeFileSync(url, JSON.stringify(data, null, ' ')) } catch(e) { - console.error('(ERROR) could not save json file to ' + url) - console.error(e.message) + if (typeof(errorCallback) === 'function') { + errorCallback(e) + } else { + console.error('(ERROR) could not save json file to ' + url) + console.error(e.message) + } } }, console: console,