Skip to content

Commit

Permalink
feat: retain newlines in string jsons
Browse files Browse the repository at this point in the history
This feature will automatically detect whether or not the
existing json string ends in a newline and if it does - then
when stringifying the json, it will append a newline character.

This is useful for occasions where, for example, a developer
desires to have trailing newlines; we want to maintain that
preference.
  • Loading branch information
keithamus committed Feb 14, 2016
1 parent 8f0e91f commit 1cc5b75
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
var sortObjectKeys = require('sort-object-keys');
function sortPackageJson(packageJson) {
var wasString = false;
var endCharacters = '';
if (typeof packageJson === 'string') {
wasString = true;
if (packageJson.substr(-1) === '\n') {
endCharacters = '\n';
}
packageJson = JSON.parse(packageJson);
}
function sortSubKey(key, sortList) {
Expand Down Expand Up @@ -104,7 +108,7 @@ function sortPackageJson(packageJson) {
'private',
'publishConfig',
]);
return wasString ? JSON.stringify(packageJson, null, 2) : packageJson;
return wasString ? JSON.stringify(packageJson, null, 2) + endCharacters : packageJson;
}
module.exports = sortPackageJson;
module.exports.sortPackageJson = sortPackageJson;
Expand Down
3 changes: 3 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,7 @@ require('fs').readFile('./package.json', 'utf8', function (error, contents) {
'posttest',
'watch',
])

assert.equal(sortPackageJson('{}\n'), '{}\n');
assert.equal(sortPackageJson('{"foo":"bar"}\n'), '{\n "foo": "bar"\n}\n');
});

0 comments on commit 1cc5b75

Please sign in to comment.