Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for dotted keys. #5

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
22 changes: 22 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"rules": {
"indent": [2, 2],
"quotes": [2, "single"],
"linebreak-style": [2, "unix"],
"semi": [2, "always"],
"curly": [2, "multi-line"],
"handle-callback-err": [2, "^err"],
"strict": 0,
"eqeqeq": 0,
"eol-last": 0,
"dot-notation": 0,
"no-mixed-requires": 0,
"no-multi-spaces": 0,
"no-use-before-define": 0,
"no-underscore-dangle": 0
},
"env": {
"node": true,
"browser": true
}
}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules/
test/tmp/*.json
*.log
4 changes: 4 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
test/
test.js
*.log
6 changes: 6 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
sudo: false
language: node_js
node_js:
- "0.10"
- "0.12"
- "iojs"
171 changes: 171 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
var fs = require('fs');
var path = require('path');
var findWhitespace = /^(\s+)/;

var File = exports.File = function(filePath) {
this.path = path.normalize(filePath);
};

exports.read = function(filePath, callback) {
var file = new File(filePath);
if (callback) {
file.read(callback);
} else {
file.readSync();
}
return file;
};

File.prototype.data = undefined;
File.prototype.indent = null;

// ------------------------------------------------------------------
// File I/O

/**
* Combines read/write method and creates new file
* if one doesn't exist
*
* @param {function} callback - invoked when file's been read into object
*/
File.prototype.update = function(callback) {
this.read(function(err, json) {
// ignore nonexistent file error
if (err && err.code != 'ENOENT') {
return callback.call(this, err);
}

// invoke callback within file instance
// with `write` function as `save` callback
callback.call(this, null, this.write.bind(this));
}.bind(this));
};

File.prototype.updateSync = function(callback) {
var content;

try {
content = fs.readFileSync(this.path, 'utf8');
} catch (e) {
if (e.code != 'ENOENT') throw e;
content = '{}';
}

this._processJson(content);
};

File.prototype.read = function(callback) {
fs.readFile(this.path, 'utf8', this._afterRead.bind(this, callback));
};

File.prototype._afterRead = function(callback, err, json) {
if (err) {
return callback(err);
}
this._processJson(json);
callback();
};

File.prototype.readSync = function() {
this._processJson(
fs.readFileSync(this.path, 'utf8')
);
};

File.prototype._processJson = function(json) {
this.data = JSON.parse(json);
this.indent = determineWhitespace(json);
};

File.prototype.write = function(callback, replacer, space) {
var space = space || this.indent,
json = JSON.stringify(this.data, replacer, space);
fs.writeFile(this.path, json, callback);
};

File.prototype.writeSync = function(replacer, space) {
var space = space || this.indent,
json = JSON.stringify(this.data, replacer, space);
fs.writeFileSync(this.path, json);
};

// ------------------------------------------------------------------
// Property editing

File.prototype.get = function(key) {
return this._resolve(key, function(scope, key, value) {
return value;
});
};

File.prototype.set = function(key, value) {
this._resolve(key, function(scope, key) {
scope[key] = value;
});
return this;
};

/**
* Remove key from the object
*
* @param {mixed} key - key to delete
* @returns {File} returns itself for chaining
*/
File.prototype.del = function(key) {
this._resolve(key, function(scope, key) {
delete scope[key];
});
return this;
};

// Has a callback, but is NOT async
File.prototype._resolve = function(key, callback) {
var current, parseable, keys, lastKey;

// init top node
this.data = this.data || {};

// get slider reference
current = this.data;

// separate for traversable and non-traversable parts
parseable = key.split(/\[(.*)\]/, 2);

// get traversable keys
keys = parseable[0] ? parseable[0].split('.') : [];

// last key or non-traversable part
lastKey = parseable[1] || keys.pop();

// traverse
keys.forEach(function(key) {

// if key doesn't exist (or not referencing object), create it as empty object
if (typeof current[key] != 'object') {
current[key] = {};
}

// go deeper
current = current[key];
});

return callback(current, lastKey, current[lastKey]);
};

// ------------------------------------------------------------------

function determineWhitespace(contents) {
var whitespace = 0;
contents = contents.split('\n');
for (var i = 0, c = contents.length; i < c; i++) {
var match = findWhitespace.exec(contents);
if (match && typeof match[1] === 'string') {
if (match[1][0] === '\t') {
whitespace = '\t';
break;
} else if (match[1].length < whitespace || ! whitespace) {
whitespace = match[1].length;
}
}
}
}
104 changes: 0 additions & 104 deletions lib/index.js

This file was deleted.

27 changes: 18 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,29 @@
{
"name": "json-file",
"version": "0.1.0",
"description": "A module for modifiying JSON files",
"main": "lib/index.js",
"name": "jsonfile2",
"version": "2.1.0",
"description": "A module for modifying JSON files (extended from npm.org/json-file)",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "cp test/input.json test/tmp/update.json && node test.js",
"lint": "eslint -c .eslintrc *.js"
},
"pre-commit": [
"lint",
"test"
],
"repository": {
"type": "git",
"url": "git://github.com/UmbraEngineering/json-file"
"url": "git://github.com/alexindigo/jsonfile2"
},
"keywords": [
"json",
"file",
"i/o"
"keys"
],
"author": "James Brumond",
"license": "MIT"
"author": "Alex Indigo <iam@alexindigo.com>",
"license": "MIT",
"devDependencies": {
"eslint": "^1.6.0",
"pre-commit": "^1.1.1"
}
}
Loading