pax_global_header00006660000000000000000000000064131560312270014512gustar00rootroot0000000000000052 comment=840bcc77f4e0bfcdf44c32895af42de97e80e3a8 node-jsonfile-4.0.0/000077500000000000000000000000001315603122700142475ustar00rootroot00000000000000node-jsonfile-4.0.0/.editorconfig000066400000000000000000000001621315603122700167230ustar00rootroot00000000000000root = true [*] trim_trailing_whitespace = true insert_final_newline = true indent_style = space indent_size = 2 node-jsonfile-4.0.0/.gitignore000066400000000000000000000000301315603122700162300ustar00rootroot00000000000000node_modules/ /.project node-jsonfile-4.0.0/.npmignore000066400000000000000000000000371315603122700162460ustar00rootroot00000000000000test/ .travis.yml appveyor.yml node-jsonfile-4.0.0/.travis.yml000066400000000000000000000002741315603122700163630ustar00rootroot00000000000000sudo: false language: node_js node_js: - "4" - "6" - "8" matrix: include: - node_js: "8" env: TEST_SUITE=lint env: - TEST_SUITE=unit script: npm run-script $TEST_SUITE node-jsonfile-4.0.0/CHANGELOG.md000066400000000000000000000174261315603122700160720ustar00rootroot000000000000004.0.0 / 2017-07-12 ------------------ - **BREAKING:** Remove global `spaces` option. - **BREAKING:** Drop support for Node 0.10, 0.12, and io.js. - Remove undocumented `passParsingErrors` option. - Added `EOL` override option to `writeFile` when using `spaces`. [#89] 3.0.1 / 2017-07-05 ------------------ - Fixed bug in `writeFile` when there was a serialization error & no callback was passed. In previous versions, an empty file would be written; now no file is written. 3.0.0 / 2017-04-25 ------------------ - Changed behavior of `throws` option for `readFileSync`; now does not throw filesystem errors when `throws` is `false` 2.4.0 / 2016-09-15 ------------------ ### Changed - added optional support for `graceful-fs` [#62] 2.3.1 / 2016-05-13 ------------------ - fix to support BOM. [#45][#45] 2.3.0 / 2016-04-16 ------------------ - add `throws` to `readFile()`. See [#39][#39] - add support for any arbitrary `fs` module. Useful with [mock-fs](https://www.npmjs.com/package/mock-fs) 2.2.3 / 2015-10-14 ------------------ - include file name in parse error. See: https://github.com/jprichardson/node-jsonfile/pull/34 2.2.2 / 2015-09-16 ------------------ - split out tests into separate files - fixed `throws` when set to `true` in `readFileSync()`. See: https://github.com/jprichardson/node-jsonfile/pull/33 2.2.1 / 2015-06-25 ------------------ - fixed regression when passing in string as encoding for options in `writeFile()` and `writeFileSync()`. See: https://github.com/jprichardson/node-jsonfile/issues/28 2.2.0 / 2015-06-25 ------------------ - added `options.spaces` to `writeFile()` and `writeFileSync()` 2.1.2 / 2015-06-22 ------------------ - fixed if passed `readFileSync(file, 'utf8')`. See: https://github.com/jprichardson/node-jsonfile/issues/25 2.1.1 / 2015-06-19 ------------------ - fixed regressions if `null` is passed for options. See: https://github.com/jprichardson/node-jsonfile/issues/24 2.1.0 / 2015-06-19 ------------------ - cleanup: JavaScript Standard Style, rename files, dropped terst for assert - methods now support JSON revivers/replacers 2.0.1 / 2015-05-24 ------------------ - update license attribute https://github.com/jprichardson/node-jsonfile/pull/21 2.0.0 / 2014-07-28 ------------------ * added `\n` to end of file on write. [#14](https://github.com/jprichardson/node-jsonfile/pull/14) * added `options.throws` to `readFileSync()` * dropped support for Node v0.8 1.2.0 / 2014-06-29 ------------------ * removed semicolons * bugfix: passed `options` to `fs.readFile` and `fs.readFileSync`. This technically changes behavior, but changes it according to docs. [#12][#12] 1.1.1 / 2013-11-11 ------------------ * fixed catching of callback bug (ffissore / #5) 1.1.0 / 2013-10-11 ------------------ * added `options` param to methods, (seanodell / #4) 1.0.1 / 2013-09-05 ------------------ * removed `homepage` field from package.json to remove NPM warning 1.0.0 / 2013-06-28 ------------------ * added `.npmignore`, #1 * changed spacing default from `4` to `2` to follow Node conventions 0.0.1 / 2012-09-10 ------------------ * Initial release. [#89]: https://github.com/jprichardson/node-jsonfile/pull/89 [#45]: https://github.com/jprichardson/node-jsonfile/issues/45 "Reading of UTF8-encoded (w/ BOM) files fails" [#44]: https://github.com/jprichardson/node-jsonfile/issues/44 "Extra characters in written file" [#43]: https://github.com/jprichardson/node-jsonfile/issues/43 "Prettyfy json when written to file" [#42]: https://github.com/jprichardson/node-jsonfile/pull/42 "Moved fs.readFileSync within the try/catch" [#41]: https://github.com/jprichardson/node-jsonfile/issues/41 "Linux: Hidden file not working" [#40]: https://github.com/jprichardson/node-jsonfile/issues/40 "autocreate folder doesn't work from Path-value" [#39]: https://github.com/jprichardson/node-jsonfile/pull/39 "Add `throws` option for readFile (async)" [#38]: https://github.com/jprichardson/node-jsonfile/pull/38 "Update README.md writeFile[Sync] signature" [#37]: https://github.com/jprichardson/node-jsonfile/pull/37 "support append file" [#36]: https://github.com/jprichardson/node-jsonfile/pull/36 "Add typescript definition file." [#35]: https://github.com/jprichardson/node-jsonfile/pull/35 "Add typescript definition file." [#34]: https://github.com/jprichardson/node-jsonfile/pull/34 "readFile JSON parse error includes filename" [#33]: https://github.com/jprichardson/node-jsonfile/pull/33 "fix throw->throws typo in readFileSync()" [#32]: https://github.com/jprichardson/node-jsonfile/issues/32 "readFile & readFileSync can possible have strip-comments as an option?" [#31]: https://github.com/jprichardson/node-jsonfile/pull/31 "[Modify] Support string include is unicode escape string" [#30]: https://github.com/jprichardson/node-jsonfile/issues/30 "How to use Jsonfile package in Meteor.js App?" [#29]: https://github.com/jprichardson/node-jsonfile/issues/29 "writefile callback if no error?" [#28]: https://github.com/jprichardson/node-jsonfile/issues/28 "writeFile options argument broken " [#27]: https://github.com/jprichardson/node-jsonfile/pull/27 "Use svg instead of png to get better image quality" [#26]: https://github.com/jprichardson/node-jsonfile/issues/26 "Breaking change to fs-extra" [#25]: https://github.com/jprichardson/node-jsonfile/issues/25 "support string encoding param for read methods" [#24]: https://github.com/jprichardson/node-jsonfile/issues/24 "readFile: Passing in null options with a callback throws an error" [#23]: https://github.com/jprichardson/node-jsonfile/pull/23 "Add appendFile and appendFileSync" [#22]: https://github.com/jprichardson/node-jsonfile/issues/22 "Default value for spaces in readme.md is outdated" [#21]: https://github.com/jprichardson/node-jsonfile/pull/21 "Update license attribute" [#20]: https://github.com/jprichardson/node-jsonfile/issues/20 "Add simple caching functionallity" [#19]: https://github.com/jprichardson/node-jsonfile/pull/19 "Add appendFileSync method" [#18]: https://github.com/jprichardson/node-jsonfile/issues/18 "Add updateFile and updateFileSync methods" [#17]: https://github.com/jprichardson/node-jsonfile/issues/17 "seem read & write sync has sequentially problem" [#16]: https://github.com/jprichardson/node-jsonfile/pull/16 "export spaces defaulted to null" [#15]: https://github.com/jprichardson/node-jsonfile/issues/15 "`jsonfile.spaces` should default to `null`" [#14]: https://github.com/jprichardson/node-jsonfile/pull/14 "Add EOL at EOF" [#13]: https://github.com/jprichardson/node-jsonfile/issues/13 "Add a final newline" [#12]: https://github.com/jprichardson/node-jsonfile/issues/12 "readFile doesn't accept options" [#11]: https://github.com/jprichardson/node-jsonfile/pull/11 "Added try,catch to readFileSync" [#10]: https://github.com/jprichardson/node-jsonfile/issues/10 "No output or error from writeFile" [#9]: https://github.com/jprichardson/node-jsonfile/pull/9 "Change 'js' to 'jf' in example." [#8]: https://github.com/jprichardson/node-jsonfile/pull/8 "Updated forgotten module.exports to me." [#7]: https://github.com/jprichardson/node-jsonfile/pull/7 "Add file name in error message" [#6]: https://github.com/jprichardson/node-jsonfile/pull/6 "Use graceful-fs when possible" [#5]: https://github.com/jprichardson/node-jsonfile/pull/5 "Jsonfile doesn't behave nicely when used inside a test suite." [#4]: https://github.com/jprichardson/node-jsonfile/pull/4 "Added options parameter to writeFile and writeFileSync" [#3]: https://github.com/jprichardson/node-jsonfile/issues/3 "test2" [#2]: https://github.com/jprichardson/node-jsonfile/issues/2 "homepage field must be a string url. Deleted." [#1]: https://github.com/jprichardson/node-jsonfile/pull/1 "adding an `.npmignore` file" node-jsonfile-4.0.0/LICENSE000066400000000000000000000021261315603122700152550ustar00rootroot00000000000000(The MIT License) Copyright (c) 2012-2015, JP Richardson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node-jsonfile-4.0.0/README.md000066400000000000000000000103261315603122700155300ustar00rootroot00000000000000Node.js - jsonfile ================ Easily read/write JSON files. [![npm Package](https://img.shields.io/npm/v/jsonfile.svg?style=flat-square)](https://www.npmjs.org/package/jsonfile) [![build status](https://secure.travis-ci.org/jprichardson/node-jsonfile.svg)](http://travis-ci.org/jprichardson/node-jsonfile) [![windows Build status](https://img.shields.io/appveyor/ci/jprichardson/node-jsonfile/master.svg?label=windows%20build)](https://ci.appveyor.com/project/jprichardson/node-jsonfile/branch/master) Standard JavaScript Why? ---- Writing `JSON.stringify()` and then `fs.writeFile()` and `JSON.parse()` with `fs.readFile()` enclosed in `try/catch` blocks became annoying. Installation ------------ npm install --save jsonfile API --- ### readFile(filename, [options], callback) `options` (`object`, default `undefined`): Pass in any `fs.readFile` options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse). - `throws` (`boolean`, default: `true`). If `JSON.parse` throws an error, pass this error to the callback. If `false`, returns `null` for the object. ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' jsonfile.readFile(file, function(err, obj) { console.dir(obj) }) ``` ### readFileSync(filename, [options]) `options` (`object`, default `undefined`): Pass in any `fs.readFileSync` options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse). - `throws` (`boolean`, default: `true`). If an error is encountered reading or parsing the file, throw the error. If `false`, returns `null` for the object. ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' console.dir(jsonfile.readFileSync(file)) ``` ### writeFile(filename, obj, [options], callback) `options`: Pass in any `fs.writeFile` options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces` and override `EOL` string. ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFile(file, obj, function (err) { console.error(err) }) ``` **formatting with spaces:** ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFile(file, obj, {spaces: 2}, function(err) { console.error(err) }) ``` **overriding EOL:** ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFile(file, obj, {spaces: 2, EOL: '\r\n'}, function(err) { console.error(err) }) ``` **appending to an existing JSON file:** You can use `fs.writeFile` option `{flag: 'a'}` to achieve this. ```js var jsonfile = require('jsonfile') var file = '/tmp/mayAlreadyExistedData.json' var obj = {name: 'JP'} jsonfile.writeFile(file, obj, {flag: 'a'}, function (err) { console.error(err) }) ``` ### writeFileSync(filename, obj, [options]) `options`: Pass in any `fs.writeFileSync` options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces` and override `EOL` string. ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFileSync(file, obj) ``` **formatting with spaces:** ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFileSync(file, obj, {spaces: 2}) ``` **overriding EOL:** ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFileSync(file, obj, {spaces: 2, EOL: '\r\n'}) ``` **appending to an existing JSON file:** You can use `fs.writeFileSync` option `{flag: 'a'}` to achieve this. ```js var jsonfile = require('jsonfile') var file = '/tmp/mayAlreadyExistedData.json' var obj = {name: 'JP'} jsonfile.writeFileSync(file, obj, {flag: 'a'}) ``` License ------- (MIT License) Copyright 2012-2016, JP Richardson node-jsonfile-4.0.0/appveyor.yml000066400000000000000000000010731315603122700166400ustar00rootroot00000000000000# Test against this version of Node.js environment: matrix: # node.js - nodejs_version: "4" - nodejs_version: "6" - nodejs_version: "8" # Install scripts. (runs after repo cloning) install: # Get the latest stable version of Node.js or io.js - ps: Install-Product node $env:nodejs_version # install modules - npm config set loglevel warn - npm install --silent # Post-install test scripts. test_script: # Output useful info for debugging. - node --version - npm --version # run tests - npm test # Don't actually build. build: off node-jsonfile-4.0.0/index.js000066400000000000000000000054261315603122700157230ustar00rootroot00000000000000var _fs try { _fs = require('graceful-fs') } catch (_) { _fs = require('fs') } function readFile (file, options, callback) { if (callback == null) { callback = options options = {} } if (typeof options === 'string') { options = {encoding: options} } options = options || {} var fs = options.fs || _fs var shouldThrow = true if ('throws' in options) { shouldThrow = options.throws } fs.readFile(file, options, function (err, data) { if (err) return callback(err) data = stripBom(data) var obj try { obj = JSON.parse(data, options ? options.reviver : null) } catch (err2) { if (shouldThrow) { err2.message = file + ': ' + err2.message return callback(err2) } else { return callback(null, null) } } callback(null, obj) }) } function readFileSync (file, options) { options = options || {} if (typeof options === 'string') { options = {encoding: options} } var fs = options.fs || _fs var shouldThrow = true if ('throws' in options) { shouldThrow = options.throws } try { var content = fs.readFileSync(file, options) content = stripBom(content) return JSON.parse(content, options.reviver) } catch (err) { if (shouldThrow) { err.message = file + ': ' + err.message throw err } else { return null } } } function stringify (obj, options) { var spaces var EOL = '\n' if (typeof options === 'object' && options !== null) { if (options.spaces) { spaces = options.spaces } if (options.EOL) { EOL = options.EOL } } var str = JSON.stringify(obj, options ? options.replacer : null, spaces) return str.replace(/\n/g, EOL) + EOL } function writeFile (file, obj, options, callback) { if (callback == null) { callback = options options = {} } options = options || {} var fs = options.fs || _fs var str = '' try { str = stringify(obj, options) } catch (err) { // Need to return whether a callback was passed or not if (callback) callback(err, null) return } fs.writeFile(file, str, options, callback) } function writeFileSync (file, obj, options) { options = options || {} var fs = options.fs || _fs var str = stringify(obj, options) // not sure if fs.writeFileSync returns anything, but just in case return fs.writeFileSync(file, str, options) } function stripBom (content) { // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified if (Buffer.isBuffer(content)) content = content.toString('utf8') content = content.replace(/^\uFEFF/, '') return content } var jsonfile = { readFile: readFile, readFileSync: readFileSync, writeFile: writeFile, writeFileSync: writeFileSync } module.exports = jsonfile node-jsonfile-4.0.0/package.json000066400000000000000000000013071315603122700165360ustar00rootroot00000000000000{ "name": "jsonfile", "version": "4.0.0", "description": "Easily read/write JSON files.", "repository": { "type": "git", "url": "git@github.com:jprichardson/node-jsonfile.git" }, "keywords": [ "read", "write", "file", "json", "fs", "fs-extra" ], "author": "JP Richardson ", "license": "MIT", "dependencies": {}, "optionalDependencies": { "graceful-fs": "^4.1.6" }, "devDependencies": { "mocha": "2.x", "rimraf": "^2.4.0", "standard": "^10.0.3" }, "main": "index.js", "files": [ "index.js" ], "scripts": { "lint": "standard", "test": "npm run lint && npm run unit", "unit": "mocha" } } node-jsonfile-4.0.0/test/000077500000000000000000000000001315603122700152265ustar00rootroot00000000000000node-jsonfile-4.0.0/test/read-file-sync.test.js000066400000000000000000000100021315603122700213350ustar00rootroot00000000000000var assert = require('assert') var fs = require('fs') var os = require('os') var path = require('path') var rimraf = require('rimraf') var jf = require('../') /* global describe it beforeEach afterEach */ describe('+ readFileSync()', function () { var TEST_DIR beforeEach(function (done) { TEST_DIR = path.join(os.tmpdir(), 'jsonfile-tests-readfile-sync') rimraf.sync(TEST_DIR) fs.mkdir(TEST_DIR, done) }) afterEach(function (done) { rimraf.sync(TEST_DIR) done() }) it('should read and parse JSON', function () { var file = path.join(TEST_DIR, 'somefile3.json') var obj = {name: 'JP'} fs.writeFileSync(file, JSON.stringify(obj)) try { var obj2 = jf.readFileSync(file) assert.equal(obj2.name, obj.name) } catch (err) { assert(err) } }) describe('> when invalid JSON', function () { it('should include the filename in the error', function () { var fn = 'somefile.json' var file = path.join(TEST_DIR, fn) fs.writeFileSync(file, '{') assert.throws(function () { jf.readFileSync(file) }, function (err) { assert(err instanceof Error) assert(err.message.match(fn)) return true }) }) }) describe('> when invalid JSON and throws set to false', function () { it('should return null', function () { var file = path.join(TEST_DIR, 'somefile4-invalid.json') var data = '{not valid JSON' fs.writeFileSync(file, data) assert.throws(function () { jf.readFileSync(file) }) var obj = jf.readFileSync(file, {throws: false}) assert.strictEqual(obj, null) }) }) describe('> when invalid JSON and throws set to true', function () { it('should throw an exception', function () { var file = path.join(TEST_DIR, 'somefile4-invalid.json') var data = '{not valid JSON' fs.writeFileSync(file, data) assert.throws(function () { jf.readFileSync(file, {throws: true}) }) }) }) describe('> when json file is missing and throws set to false', function () { it('should return null', function () { var file = path.join(TEST_DIR, 'somefile4-invalid.json') var obj = jf.readFileSync(file, {throws: false}) assert.strictEqual(obj, null) }) }) describe('> when json file is missing and throws set to true', function () { it('should throw an exception', function () { var file = path.join(TEST_DIR, 'somefile4-invalid.json') assert.throws(function () { jf.readFileSync(file, {throws: true}) }) }) }) describe('> when JSON reviver is set', function () { it('should transform the JSON', function () { var file = path.join(TEST_DIR, 'somefile.json') var sillyReviver = function (k, v) { if (typeof v !== 'string') return v if (v.indexOf('date:') < 0) return v return new Date(v.split('date:')[1]) } var obj = { name: 'jp', day: 'date:2015-06-19T11:41:26.815Z' } fs.writeFileSync(file, JSON.stringify(obj)) var data = jf.readFileSync(file, {reviver: sillyReviver}) assert.strictEqual(data.name, 'jp') assert(data.day instanceof Date) assert.strictEqual(data.day.toISOString(), '2015-06-19T11:41:26.815Z') }) }) describe('> when passing encoding string as option', function () { it('should not throw an error', function () { var file = path.join(TEST_DIR, 'somefile.json') var obj = { name: 'jp' } fs.writeFileSync(file, JSON.stringify(obj)) try { var data = jf.readFileSync(file, 'utf8') } catch (err) { assert.ifError(err) } assert.strictEqual(data.name, 'jp') }) }) describe('> w/ BOM', function () { it('should properly parse', function () { var file = path.join(TEST_DIR, 'file-bom.json') var obj = { name: 'JP' } fs.writeFileSync(file, '\uFEFF' + JSON.stringify(obj)) var data = jf.readFileSync(file) assert.deepEqual(obj, data) }) }) }) node-jsonfile-4.0.0/test/read-file.test.js000066400000000000000000000111451315603122700203740ustar00rootroot00000000000000var assert = require('assert') var fs = require('fs') var os = require('os') var path = require('path') var rimraf = require('rimraf') var jf = require('../') /* global describe it beforeEach afterEach */ describe('+ readFile()', function () { var TEST_DIR beforeEach(function (done) { TEST_DIR = path.join(os.tmpdir(), 'jsonfile-tests-readfile') rimraf.sync(TEST_DIR) fs.mkdir(TEST_DIR, done) }) afterEach(function (done) { rimraf.sync(TEST_DIR) done() }) it('should read and parse JSON', function (done) { var file = path.join(TEST_DIR, 'somefile.json') var obj = {name: 'JP'} fs.writeFileSync(file, JSON.stringify(obj)) jf.readFile(file, function (err, obj2) { assert.ifError(err) assert.equal(obj2.name, obj.name) done() }) }) describe('> when invalid JSON', function () { it('should include the filename in the error', function (done) { var fn = 'somefile.json' var file = path.join(TEST_DIR, fn) fs.writeFileSync(file, '{') jf.readFile(file, function (err, obj2) { assert(err instanceof Error) assert(err.message.match(fn)) done() }) }) }) describe('> when invalid JSON and throws set to false', function () { it('should return null and no error', function (done) { var fn = 'somefile4-invalid.json' var file = path.join(TEST_DIR, fn) var data = '{not valid JSON' var bothDone = false fs.writeFileSync(file, data) jf.readFile(file, function (err, obj2) { assert(err instanceof Error) assert(err.message.match(fn)) if (bothDone) { done() } bothDone = true }) jf.readFile(file, {throws: false}, function (err, obj2) { assert.ifError(err) assert.strictEqual(obj2, null) if (bothDone) { done() } bothDone = true }) }) }) describe('> when invalid JSON and throws set to true', function () { it('should return an error', function (done) { var fn = 'somefile4-invalid.json' var file = path.join(TEST_DIR, fn) var data = '{not valid JSON' var bothDone = false fs.writeFileSync(file, data) jf.readFile(file, function (err, obj2) { assert(err instanceof Error) assert(err.message.match(fn)) if (bothDone) { done() } bothDone = true }) jf.readFile(file, {throws: true}, function (err, obj2) { assert(err instanceof Error) assert(err.message.match(fn)) if (bothDone) { done() } bothDone = true }) }) }) describe('> when JSON reviver is set', function () { it('should transform the JSON', function (done) { var file = path.join(TEST_DIR, 'somefile.json') var sillyReviver = function (k, v) { if (typeof v !== 'string') return v if (v.indexOf('date:') < 0) return v return new Date(v.split('date:')[1]) } var obj = { name: 'jp', day: 'date:2015-06-19T11:41:26.815Z' } fs.writeFileSync(file, JSON.stringify(obj)) jf.readFile(file, {reviver: sillyReviver}, function (err, data) { assert.ifError(err) assert.strictEqual(data.name, 'jp') assert(data.day instanceof Date) assert.strictEqual(data.day.toISOString(), '2015-06-19T11:41:26.815Z') done() }) }) }) describe('> when passing null and callback', function () { it('should not throw an error', function (done) { var file = path.join(TEST_DIR, 'somefile.json') var obj = { name: 'jp' } fs.writeFileSync(file, JSON.stringify(obj)) jf.readFile(file, null, function (err) { assert.ifError(err) assert.strictEqual(obj.name, 'jp') done() }) }) }) describe('> when passing encoding string as option', function () { it('should not throw an error', function (done) { var file = path.join(TEST_DIR, 'somefile.json') var obj = { name: 'jp' } fs.writeFileSync(file, JSON.stringify(obj)) jf.readFile(file, 'utf8', function (err) { assert.ifError(err) assert.strictEqual(obj.name, 'jp') done() }) }) }) describe('> w/ BOM', function () { it('should properly parse', function (done) { var file = path.join(TEST_DIR, 'file-bom.json') var obj = { name: 'JP' } fs.writeFileSync(file, '\uFEFF' + JSON.stringify(obj)) jf.readFile(file, function (err, data) { assert.ifError(err) assert.deepEqual(obj, data) done() }) }) }) }) node-jsonfile-4.0.0/test/write-file-sync.test.js000066400000000000000000000050261315603122700215660ustar00rootroot00000000000000var assert = require('assert') var fs = require('fs') var os = require('os') var path = require('path') var rimraf = require('rimraf') var jf = require('../') /* global describe it beforeEach afterEach */ describe('+ writeFileSync()', function () { var TEST_DIR beforeEach(function (done) { TEST_DIR = path.join(os.tmpdir(), 'jsonfile-tests-writefile-sync') rimraf.sync(TEST_DIR) fs.mkdir(TEST_DIR, done) }) afterEach(function (done) { rimraf.sync(TEST_DIR) done() }) it('should serialize the JSON and write it to file', function () { var file = path.join(TEST_DIR, 'somefile4.json') var obj = {name: 'JP'} jf.writeFileSync(file, obj) var data = fs.readFileSync(file, 'utf8') var obj2 = JSON.parse(data) assert.equal(obj2.name, obj.name) assert.equal(data[data.length - 1], '\n') assert.equal(data, '{"name":"JP"}\n') }) describe('> when JSON replacer is set', function () { it('should replace JSON', function () { var file = path.join(TEST_DIR, 'somefile.json') var sillyReplacer = function (k, v) { if (!(v instanceof RegExp)) return v return 'regex:' + v.toString() } var obj = { name: 'jp', reg: new RegExp(/hello/g) } jf.writeFileSync(file, obj, {replacer: sillyReplacer}) var data = JSON.parse(fs.readFileSync(file)) assert.strictEqual(data.name, 'jp') assert.strictEqual(typeof data.reg, 'string') assert.strictEqual(data.reg, 'regex:/hello/g') }) }) describe('> when spaces passed as an option', function () { it('should write file with spaces', function () { var file = path.join(TEST_DIR, 'somefile.json') var obj = { name: 'JP' } jf.writeFileSync(file, obj, {spaces: 8}) var data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, JSON.stringify(obj, null, 8) + '\n') }) it('should use EOL override', function () { var file = path.join(TEST_DIR, 'somefile.json') var obj = { name: 'JP' } jf.writeFileSync(file, obj, {spaces: 2, EOL: '***'}) var data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, '{*** "name": "JP"***}***') }) }) describe('> when passing encoding string as options', function () { it('should not error', function () { var file = path.join(TEST_DIR, 'somefile6.json') var obj = { name: 'jp' } jf.writeFileSync(file, obj, 'utf8') var data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, JSON.stringify(obj) + '\n') }) }) }) node-jsonfile-4.0.0/test/write-file.test.js000066400000000000000000000073371315603122700206230ustar00rootroot00000000000000var assert = require('assert') var fs = require('fs') var os = require('os') var path = require('path') var rimraf = require('rimraf') var jf = require('../') /* global describe it beforeEach afterEach */ describe('+ writeFile()', function () { var TEST_DIR beforeEach(function (done) { TEST_DIR = path.join(os.tmpdir(), 'jsonfile-tests-writefile') rimraf.sync(TEST_DIR) fs.mkdir(TEST_DIR, done) }) afterEach(function (done) { rimraf.sync(TEST_DIR) done() }) it('should serialize and write JSON', function (done) { var file = path.join(TEST_DIR, 'somefile2.json') var obj = {name: 'JP'} jf.writeFile(file, obj, function (err) { assert.ifError(err) fs.readFile(file, 'utf8', function (err, data) { assert.ifError(err) var obj2 = JSON.parse(data) assert.equal(obj2.name, obj.name) // verify EOL assert.equal(data[data.length - 1], '\n') done() }) }) }) describe('> when JSON replacer is set', function () { it('should replace JSON', function (done) { var file = path.join(TEST_DIR, 'somefile.json') var sillyReplacer = function (k, v) { if (!(v instanceof RegExp)) return v return 'regex:' + v.toString() } var obj = { name: 'jp', reg: new RegExp(/hello/g) } jf.writeFile(file, obj, {replacer: sillyReplacer}, function (err) { assert.ifError(err) var data = JSON.parse(fs.readFileSync(file)) assert.strictEqual(data.name, 'jp') assert.strictEqual(typeof data.reg, 'string') assert.strictEqual(data.reg, 'regex:/hello/g') done() }) }) }) describe('> when passing null and callback', function () { it('should not throw an error', function (done) { var file = path.join(TEST_DIR, 'somefile.json') var obj = { name: 'jp' } jf.writeFile(file, obj, null, function (err) { assert.ifError(err) done() }) }) }) describe('> when spaces passed as an option', function () { it('should write file with spaces', function (done) { var file = path.join(TEST_DIR, 'somefile.json') var obj = { name: 'jp' } jf.writeFile(file, obj, {spaces: 8}, function (err) { assert.ifError(err) var data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, JSON.stringify(obj, null, 8) + '\n') done() }) }) it('should use EOL override', function (done) { var file = path.join(TEST_DIR, 'somefile.json') var obj = { name: 'jp' } jf.writeFile(file, obj, {spaces: 2, EOL: '***'}, function (err) { assert.ifError(err) var data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, '{*** "name": "jp"***}***') done() }) }) }) describe('> when passing encoding string as options', function () { it('should not error', function (done) { var file = path.join(TEST_DIR, 'somefile.json') var obj = { name: 'jp' } jf.writeFile(file, obj, 'utf8', function (err) { assert.ifError(err) var data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, JSON.stringify(obj) + '\n') done() }) }) }) // Prevent https://github.com/jprichardson/node-jsonfile/issues/81 from happening describe("> when callback isn't passed & can't serialize", function () { it('should not write an empty file', function (done) { this.slow(1100) var file = path.join(TEST_DIR, 'somefile.json') var obj1 = { name: 'JP' } var obj2 = { person: obj1 } obj1.circular = obj2 jf.writeFile(file, obj1) setTimeout(function () { assert(!fs.existsSync(file)) done() }, 1000) }) }) })