New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

self-reload-json

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

self-reload-json - npm Package Compare versions

Comparing version 0.1.0 to 0.2.0

64

index.js
(function() {
var fs = require('fs'),
path = require('path'),
util = require('util'),
EventEmitter = require('events').EventEmitter,
_ = require('underscore');
var omitKeys = _.allKeys(new EventEmitter());
omitKeys.push('stop', 'resume', 'save', 'forceUpdate');
var SelfReloadJSON = function SelfReloadJSON(options) {
EventEmitter.call(this);
switch(typeof options) {
case 'string': options = { fileName: options }; break;
case 'object': break;
default: return;
case 'object': case 'undefined': break;
default: throw new Error('Invalid options type.');
}

@@ -18,3 +25,3 @@

options = _.defaults(options, {
options = _.defaults(options || {}, {
fileName: '',

@@ -24,3 +31,5 @@ encoding: 'utf8',

method: 'native',
interval: 5000
interval: 5000,
reviver: null,
replacer: null
});

@@ -59,8 +68,16 @@

content.save = save = function save(opts) {
if(!opts) opts = {};
opts = _.defaults(opts || {}, {
encoding: options.encoding,
replacer: options.replacer,
space: null
});
updateFileLock = true;
try{
fs.writeFileSync(options.fileName, JSON.stringify(content), _.extend({
encoding: options.encoding
}, opts));
try {
fs.writeFileSync(
options.fileName,
JSON.stringify(_.omit(content, function(v, k) {
return _.contains(omitKeys, k);
}), opts.replacer, opts.space),
_.omit(opts, 'replacer', 'space')
);
} finally {

@@ -72,12 +89,16 @@ updateFileLock = false;

onFileChange = function onFileChange(a, b) {
if(a instanceof fs.Stats) {
if(a.mtime === b.mtime) return;
updateFile();
} else {
if(b !== fileName) return;
updateFile();
try {
if(a instanceof fs.Stats) {
if(a.mtime === b.mtime) return;
updateFile();
} else {
if(b !== fileName) return;
updateFile();
}
} catch(err) {
console.log(err.stack ? err.stack : err);
}
};
updateFile = function updateFile() {
content.forceUpdate = updateFile = function updateFile() {
if(updateFileLock) return;

@@ -89,13 +110,15 @@ updateFileLock = true;

});
var newContent = JSON.parse(rawFile);
var newContent = _.omit(JSON.parse(rawFile, options.reviver), function(v, k) {
return _.contains(omitKeys, k);
});
if(!options.additive) {
var removeList = _.keys(content)
var removeList = _.chain(content).keys().difference(omitKeys).value();
for(var i = 0, l = removeList.length; i < l; i++)
delete content[removeList[i]];
if(stop) content.stop = stop;
if(resume) content.resume = resume;
}
_.extendOwn(content, newContent);
content.emit('updated');
} catch(err) {
console.log(err.stack ? err.stack : err);
content.emit('error', err);
} finally {

@@ -109,3 +132,4 @@ updateFileLock = false;

util.inherits(SelfReloadJSON, EventEmitter);
module.exports = SelfReloadJSON;
})();
{
"name": "self-reload-json",
"version": "0.1.0",
"version": "0.2.0",
"description": "Self reloading JSON handler",

@@ -5,0 +5,0 @@ "main": "index.js",

Self Reload JSON
================
[![NPM](https://nodei.co/npm/self-reload-json.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/self-reload-json/)
Simple node.js module which will auto reload specified JSON file.

@@ -14,3 +16,3 @@ The instance created with this module will act as the parsed JSON object itself once loaded, you can read and write JSON content directly with the instance, also it will update automatically when the source JSON file is changed. Optional there is a save function that allows you write the modified data back into the JSON file.

```javascript
var SelfReloadJSON = require('SelfReloadJSON');
var SelfReloadJSON = require('self-reload-json');
```

@@ -20,6 +22,51 @@

-----
Not yet documented. (I will finish the documentation if I have time, sorry about that, and please read the source code temporary.)
To load a JSON file:
```javascript
var config = new SelfReloadJSON(___dirname + '/config.json');
```
Then all loaded JSON content will be the part of the instance, just change it freely, then you can use the save function to save the changes back to the JSON file.
### Methods
#### `new SelfReloadJSON(options | fileName)`
Construct the instance of self reload JSON file.
- **options** - object, see the options below:
- **fileName** - string, defines the path to the JSON file.
- **encoding** - string, defines the encoding of the JSON file. Default is `'utf8'`.
- **additive** - boolean, defines the behavior when the JSON file changed externally, set to `true` if you want to keep the removed properties in the instance. Default is `false`.
- **method** - string, must be `'native'` or `'polling'`, default is `'native'`, defines what method to determine the changes of JSON file. `'native'` mode will use system API to detect, and `'polling'` mode will poll the modefied time of the JSON file. In the most case 'native' is more efficient, but some of the operating system does not support this, in this case `'polling'` should be used as fallback.
- **interval** - integer, the checking interval if 'polling' mode is used. Default is `5000` milliseconds.
- **reviver** - function, the [reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter) function when parsing JSON. Default is `null`.
- **replacer** - either number, string or function, the [replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) function when converting JSON object back to string. You can override this option while calling `save` (see below). Default is `null`.
#### `stop()`
Stop watching the changes of the JSON file. You can use `resume` to continue watching the changes.
#### `resume()`
Start to watch the changes of the JSON file. In default, this is automatically called after instance construction.
#### `forceUpdate()`
Force update the JSON file.
#### `save(options)`
Write the changes back to the JSON file.
- **options** - object, optional, will use default or inherted settings if this is not defined, see the options below:
- **encoding** - string, defines the encoding of the JSON file. Default value is inherted from the constructor options.
- **replacer** - either number, string or function, see the description in the option with same name in constructor. Default value is inherted from there.
- **space** - either number or string, [space](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument) parameter passed to `JSON.stringify`. Default is `null`.
### Events
As this class is also inherits from `EventHandler` class of Node.JS, it will expose 2 event types with event handler.
#### `on('updated', function() { ... })`
This event will be emitted after the JSON content refreshed.
#### `on('error', function(err) { ... })`
This event will be emitted while error occured when loading the updated JSON file. The `err` parameter will be the error thrown by the updater.
Limit
-----
If a property name conflicts with the function names described above, they will be ignored.
license
-------
[MIT](LICENSE)
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc