diff --git a/index.js b/index.js index fceff885..45e5d842 100755 --- a/index.js +++ b/index.js @@ -83,6 +83,7 @@ const defaultNpmScripts = [ function sortPackageJson(packageJson, options = {}) { const determinedSortOrder = options.sortOrder || sortOrder; let wasString = false; + let hasWindowsNewlines = false; let endCharacters = ''; let indentLevel = 2; if (typeof packageJson === 'string') { @@ -91,6 +92,8 @@ function sortPackageJson(packageJson, options = {}) { if (packageJson.substr(-1) === '\n') { endCharacters = '\n'; } + const newlineMatch = packageJson.match(/(\r?\n)/); + hasWindowsNewlines = (newlineMatch && newlineMatch[0]) === '\r\n'; packageJson = JSON.parse(packageJson); } @@ -185,9 +188,14 @@ function sortPackageJson(packageJson, options = {}) { sortSubKey('private'); sortSubKey('publishConfig'); packageJson = sortObjectKeys(packageJson, determinedSortOrder); - return wasString - ? JSON.stringify(packageJson, null, indentLevel) + endCharacters - : packageJson; + if (wasString) { + let result = JSON.stringify(packageJson, null, indentLevel) + endCharacters; + if (hasWindowsNewlines) { + result = result.replace(/\n/g, '\r\n'); + } + return result; + } + return packageJson; } module.exports = sortPackageJson; module.exports.sortPackageJson = sortPackageJson; diff --git a/test.js b/test.js index 5c13bc03..9113207d 100644 --- a/test.js +++ b/test.js @@ -94,7 +94,9 @@ fs.readFile('./package.json', 'utf8', (error, contents) => { ['engines', 'name'] ); + assert.equal(sortPackageJson('{}'), '{}'); assert.equal(sortPackageJson('{}\n'), '{}\n'); + assert.equal(sortPackageJson('{}\r\n'), '{}\r\n'); assert.equal(sortPackageJson('{"foo":"bar"}\n'), '{"foo":"bar"}\n'); assert.equal( @@ -105,5 +107,9 @@ fs.readFile('./package.json', 'utf8', (error, contents) => { sortPackageJson('{\n "name": "foo",\n "version": "1.0.0"\n}'), '{\n "name": "foo",\n "version": "1.0.0"\n}' ); + assert.equal( + sortPackageJson('{\r\n "foo": "bar"\r\n}\r\n'), + '{\r\n "foo": "bar"\r\n}\r\n' + ); });