pax_global_header00006660000000000000000000000064137473133770014531gustar00rootroot0000000000000052 comment=9c6478a85899a9318547a6e9514b0403166d8c5c node-jsonfile-6.1.0/000077500000000000000000000000001374731337700142715ustar00rootroot00000000000000node-jsonfile-6.1.0/.editorconfig000066400000000000000000000001621374731337700167450ustar00rootroot00000000000000root = true [*] trim_trailing_whitespace = true insert_final_newline = true indent_style = space indent_size = 2 node-jsonfile-6.1.0/.gitignore000066400000000000000000000000421374731337700162550ustar00rootroot00000000000000node_modules/ /.project .vscode/ node-jsonfile-6.1.0/.travis.yml000066400000000000000000000002671374731337700164070ustar00rootroot00000000000000sudo: false language: node_js node_js: - "10" - "12" matrix: include: - node_js: "12" env: TEST_SUITE=lint env: - TEST_SUITE=unit script: npm run-script $TEST_SUITE node-jsonfile-6.1.0/CHANGELOG.md000066400000000000000000000216301374731337700161040ustar00rootroot000000000000006.1.0 / 2020-10-31 ------------------ - Add `finalEOL` option to disable writing final EOL ([#115](https://github.com/jprichardson/node-jsonfile/issues/115), [#137](https://github.com/jprichardson/node-jsonfile/pull/137)) - Update dependency ([#138](https://github.com/jprichardson/node-jsonfile/pull/138)) 6.0.1 / 2020-03-07 ------------------ - Update dependency ([#130](https://github.com/jprichardson/node-jsonfile/pull/130)) - Fix code style ([#129](https://github.com/jprichardson/node-jsonfile/pull/129)) 6.0.0 / 2020-02-24 ------------------ - **BREAKING:** Drop support for Node 6 & 8 ([#128](https://github.com/jprichardson/node-jsonfile/pull/128)) - **BREAKING:** Do not allow passing `null` as options to `readFile()` or `writeFile()` ([#128](https://github.com/jprichardson/node-jsonfile/pull/128)) - Refactor internals ([#128](https://github.com/jprichardson/node-jsonfile/pull/128)) 5.0.0 / 2018-09-08 ------------------ - **BREAKING:** Drop Node 4 support - **BREAKING:** If no callback is passed to an asynchronous method, a promise is now returned ([#109](https://github.com/jprichardson/node-jsonfile/pull/109)) - Cleanup docs 4.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-6.1.0/LICENSE000066400000000000000000000021261374731337700152770ustar00rootroot00000000000000(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-6.1.0/README.md000066400000000000000000000143401374731337700155520ustar00rootroot00000000000000Node.js - jsonfile ================ Easily read/write JSON files in Node.js. _Note: this module cannot be used in the browser._ [![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)`](#readfilefilename-options-callback) * [`readFileSync(filename, [options])`](#readfilesyncfilename-options) * [`writeFile(filename, obj, [options], callback)`](#writefilefilename-obj-options-callback) * [`writeFileSync(filename, obj, [options])`](#writefilesyncfilename-obj-options) ---- ### readFile(filename, [options], callback) `options` (`object`, default `undefined`): Pass in any [`fs.readFile`](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback) 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 const jsonfile = require('jsonfile') const file = '/tmp/data.json' jsonfile.readFile(file, function (err, obj) { if (err) console.error(err) console.dir(obj) }) ``` You can also use this method with promises. The `readFile` method will return a promise if you do not pass a callback function. ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' jsonfile.readFile(file) .then(obj => console.dir(obj)) .catch(error => console.error(error)) ``` ---- ### readFileSync(filename, [options]) `options` (`object`, default `undefined`): Pass in any [`fs.readFileSync`](https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options) 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 const jsonfile = require('jsonfile') const file = '/tmp/data.json' console.dir(jsonfile.readFileSync(file)) ``` ---- ### writeFile(filename, obj, [options], callback) `options`: Pass in any [`fs.writeFile`](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) 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`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end. ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, function (err) { if (err) console.error(err) }) ``` Or use with promises as follows: ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj) .then(res => { console.log('Write complete') }) .catch(error => console.error(error)) ``` **formatting with spaces:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, { spaces: 2 }, function (err) { if (err) console.error(err) }) ``` **overriding EOL:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, { spaces: 2, EOL: '\r\n' }, function (err) { if (err) console.error(err) }) ``` **disabling the EOL at the end of file:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, { spaces: 2, finalEOL: false }, function (err) { if (err) console.log(err) }) ``` **appending to an existing JSON file:** You can use `fs.writeFile` option `{ flag: 'a' }` to achieve this. ```js const jsonfile = require('jsonfile') const file = '/tmp/mayAlreadyExistedData.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, { flag: 'a' }, function (err) { if (err) console.error(err) }) ``` ---- ### writeFileSync(filename, obj, [options]) `options`: Pass in any [`fs.writeFileSync`](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options) 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`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end. ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj) ``` **formatting with spaces:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj, { spaces: 2 }) ``` **overriding EOL:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj, { spaces: 2, EOL: '\r\n' }) ``` **disabling the EOL at the end of file:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj, { spaces: 2, finalEOL: false }) ``` **appending to an existing JSON file:** You can use `fs.writeFileSync` option `{ flag: 'a' }` to achieve this. ```js const jsonfile = require('jsonfile') const file = '/tmp/mayAlreadyExistedData.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj, { flag: 'a' }) ``` License ------- (MIT License) Copyright 2012-2016, JP Richardson node-jsonfile-6.1.0/appveyor.yml000066400000000000000000000010441374731337700166600ustar00rootroot00000000000000# Test against this version of Node.js environment: matrix: # node.js - nodejs_version: "10" - nodejs_version: "12" # 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-6.1.0/index.js000066400000000000000000000035541374731337700157450ustar00rootroot00000000000000let _fs try { _fs = require('graceful-fs') } catch (_) { _fs = require('fs') } const universalify = require('universalify') const { stringify, stripBom } = require('./utils') async function _readFile (file, options = {}) { if (typeof options === 'string') { options = { encoding: options } } const fs = options.fs || _fs const shouldThrow = 'throws' in options ? options.throws : true let data = await universalify.fromCallback(fs.readFile)(file, options) data = stripBom(data) let obj try { obj = JSON.parse(data, options ? options.reviver : null) } catch (err) { if (shouldThrow) { err.message = `${file}: ${err.message}` throw err } else { return null } } return obj } const readFile = universalify.fromPromise(_readFile) function readFileSync (file, options = {}) { if (typeof options === 'string') { options = { encoding: options } } const fs = options.fs || _fs const shouldThrow = 'throws' in options ? options.throws : true try { let 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 } } } async function _writeFile (file, obj, options = {}) { const fs = options.fs || _fs const str = stringify(obj, options) await universalify.fromCallback(fs.writeFile)(file, str, options) } const writeFile = universalify.fromPromise(_writeFile) function writeFileSync (file, obj, options = {}) { const fs = options.fs || _fs const str = stringify(obj, options) // not sure if fs.writeFileSync returns anything, but just in case return fs.writeFileSync(file, str, options) } const jsonfile = { readFile, readFileSync, writeFile, writeFileSync } module.exports = jsonfile node-jsonfile-6.1.0/package.json000066400000000000000000000013721374731337700165620ustar00rootroot00000000000000{ "name": "jsonfile", "version": "6.1.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": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" }, "devDependencies": { "mocha": "^8.2.0", "rimraf": "^2.4.0", "standard": "^16.0.1" }, "main": "index.js", "files": [ "index.js", "utils.js" ], "scripts": { "lint": "standard", "test": "npm run lint && npm run unit", "unit": "mocha" } } node-jsonfile-6.1.0/test/000077500000000000000000000000001374731337700152505ustar00rootroot00000000000000node-jsonfile-6.1.0/test/read-file-sync.test.js000066400000000000000000000077071374731337700214010ustar00rootroot00000000000000const assert = require('assert') const fs = require('fs') const os = require('os') const path = require('path') const rimraf = require('rimraf') const jf = require('../') /* global describe it beforeEach afterEach */ describe('+ readFileSync()', () => { let TEST_DIR beforeEach((done) => { TEST_DIR = path.join(os.tmpdir(), 'jsonfile-tests-readfile-sync') rimraf.sync(TEST_DIR) fs.mkdir(TEST_DIR, done) }) afterEach((done) => { rimraf.sync(TEST_DIR) done() }) it('should read and parse JSON', () => { const file = path.join(TEST_DIR, 'somefile3.json') const obj = { name: 'JP' } fs.writeFileSync(file, JSON.stringify(obj)) try { const obj2 = jf.readFileSync(file) assert.strictEqual(obj2.name, obj.name) } catch (err) { assert(err) } }) describe('> when invalid JSON', () => { it('should include the filename in the error', () => { const fn = 'somefile.json' const file = path.join(TEST_DIR, fn) fs.writeFileSync(file, '{') assert.throws(() => { jf.readFileSync(file) }, (err) => { assert(err instanceof Error) assert(err.message.match(fn)) return true }) }) }) describe('> when invalid JSON and throws set to false', () => { it('should return null', () => { const file = path.join(TEST_DIR, 'somefile4-invalid.json') const data = '{not valid JSON' fs.writeFileSync(file, data) assert.throws(() => { jf.readFileSync(file) }) const obj = jf.readFileSync(file, { throws: false }) assert.strictEqual(obj, null) }) }) describe('> when invalid JSON and throws set to true', () => { it('should throw an exception', () => { const file = path.join(TEST_DIR, 'somefile4-invalid.json') const data = '{not valid JSON' fs.writeFileSync(file, data) assert.throws(() => { jf.readFileSync(file, { throws: true }) }) }) }) describe('> when json file is missing and throws set to false', () => { it('should return null', () => { const file = path.join(TEST_DIR, 'somefile4-invalid.json') const obj = jf.readFileSync(file, { throws: false }) assert.strictEqual(obj, null) }) }) describe('> when json file is missing and throws set to true', () => { it('should throw an exception', () => { const file = path.join(TEST_DIR, 'somefile4-invalid.json') assert.throws(() => { jf.readFileSync(file, { throws: true }) }) }) }) describe('> when JSON reviver is set', () => { it('should transform the JSON', () => { const file = path.join(TEST_DIR, 'somefile.json') const sillyReviver = function (k, v) { if (typeof v !== 'string') return v if (v.indexOf('date:') < 0) return v return new Date(v.split('date:')[1]) } const obj = { name: 'jp', day: 'date:2015-06-19T11:41:26.815Z' } fs.writeFileSync(file, JSON.stringify(obj)) const 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', () => { it('should not throw an error', () => { const file = path.join(TEST_DIR, 'somefile.json') const obj = { name: 'jp' } fs.writeFileSync(file, JSON.stringify(obj)) let data try { data = jf.readFileSync(file, 'utf8') } catch (err) { assert.ifError(err) } assert.strictEqual(data.name, 'jp') }) }) describe('> w/ BOM', () => { it('should properly parse', () => { const file = path.join(TEST_DIR, 'file-bom.json') const obj = { name: 'JP' } fs.writeFileSync(file, `\uFEFF${JSON.stringify(obj)}`) const data = jf.readFileSync(file) assert.deepStrictEqual(obj, data) }) }) }) node-jsonfile-6.1.0/test/read-file.test.js000066400000000000000000000147571374731337700204320ustar00rootroot00000000000000const assert = require('assert') const fs = require('fs') const os = require('os') const path = require('path') const rimraf = require('rimraf') const jf = require('../') /* global describe it beforeEach afterEach */ describe('+ readFile()', () => { let TEST_DIR beforeEach((done) => { TEST_DIR = path.join(os.tmpdir(), 'jsonfile-tests-readfile') rimraf.sync(TEST_DIR) fs.mkdir(TEST_DIR, done) }) afterEach((done) => { rimraf.sync(TEST_DIR) done() }) it('should read and parse JSON', (done) => { const file = path.join(TEST_DIR, 'somefile.json') const obj = { name: 'JP' } fs.writeFileSync(file, JSON.stringify(obj)) jf.readFile(file, (err, obj2) => { assert.ifError(err) assert.strictEqual(obj2.name, obj.name) done() }) }) it('should resolve a promise with parsed JSON', (done) => { const file = path.join(TEST_DIR, 'somefile.json') const obj = { name: 'JP' } fs.writeFileSync(file, JSON.stringify(obj)) jf.readFile(file) .then((data) => { assert.strictEqual(data.name, obj.name) done() }) .catch(err => { assert.ifError(err) done() }) }) describe('> when invalid JSON', () => { let fn, file beforeEach((done) => { fn = 'somefile.json' file = path.join(TEST_DIR, fn) fs.writeFileSync(file, '{') done() }) it('should include the filename in the error', (done) => { jf.readFile(file, (err, obj2) => { assert(err instanceof Error) assert(err.message.match(fn)) done() }) }) it('should reject the promise with filename in error', (done) => { jf.readFile(file) .catch(err => { assert(err instanceof Error) assert(err.message.match(fn)) done() }) }) }) describe('> when invalid JSON and throws set to false', () => { let fn, file beforeEach((done) => { fn = 'somefile4-invalid.json' file = path.join(TEST_DIR, fn) const data = '{not valid JSON' fs.writeFileSync(file, data) done() }) it('should return null and no error', (done) => { let bothDone = false jf.readFile(file, (err, obj2) => { assert(err instanceof Error) assert(err.message.match(fn)) if (bothDone) { done() } bothDone = true }) jf.readFile(file, { throws: false }, (err, obj2) => { assert.ifError(err) assert.strictEqual(obj2, null) if (bothDone) { done() } bothDone = true }) }) it('should resolve the promise with null as data', (done) => { jf.readFile(file, { throws: false }) .then(data => { assert.strictEqual(data, null) done() }) .catch(err => { assert.ifError(err) done() }) }) }) describe('> when invalid JSON and throws set to true', () => { let fn, file beforeEach((done) => { fn = 'somefile4-invalid.json' file = path.join(TEST_DIR, fn) const data = '{not valid JSON' fs.writeFileSync(file, data) done() }) it('should return an error', (done) => { let bothDone = false jf.readFile(file, (err, obj2) => { assert(err instanceof Error) assert(err.message.match(fn)) if (bothDone) { done() } bothDone = true }) jf.readFile(file, { throws: true }, (err, obj2) => { assert(err instanceof Error) assert(err.message.match(fn)) if (bothDone) { done() } bothDone = true }) }) it('should reject the promise', (done) => { jf.readFile(file, { throws: true }) .catch(err => { assert(err instanceof Error) assert(err.message.match(fn)) done() }) }) }) describe('> when JSON reviver is set', () => { let file, sillyReviver beforeEach((done) => { file = path.join(TEST_DIR, 'somefile.json') sillyReviver = function (k, v) { if (typeof v !== 'string') return v if (v.indexOf('date:') < 0) return v return new Date(v.split('date:')[1]) } const obj = { name: 'jp', day: 'date:2015-06-19T11:41:26.815Z' } fs.writeFileSync(file, JSON.stringify(obj)) done() }) it('should transform the JSON', (done) => { jf.readFile(file, { reviver: sillyReviver }, (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() }) }) it('should resolve the promise with transformed JSON', (done) => { jf.readFile(file, { reviver: sillyReviver }) .then(data => { assert.strictEqual(data.name, 'jp') assert(data.day instanceof Date) assert.strictEqual(data.day.toISOString(), '2015-06-19T11:41:26.815Z') done() }).catch(err => { assert.ifError(err) done() }) }) }) describe('> when passing encoding string as option', () => { let file, obj beforeEach((done) => { file = path.join(TEST_DIR, 'somefile.json') obj = { name: 'jp' } fs.writeFileSync(file, JSON.stringify(obj)) done() }) it('should not throw an error', (done) => { jf.readFile(file, 'utf8', (err) => { assert.ifError(err) assert.strictEqual(obj.name, 'jp') done() }) }) it('should resolve the promise', (done) => { jf.readFile(file, 'utf8') .then(data => { assert.strictEqual(data.name, obj.name) done() }) .catch(err => { assert.ifError(err) done() }) }) }) describe('> w/ BOM', () => { let file, obj beforeEach((done) => { file = path.join(TEST_DIR, 'file-bom.json') obj = { name: 'JP' } fs.writeFileSync(file, `\uFEFF${JSON.stringify(obj)}`) done() }) it('should properly parse', (done) => { jf.readFile(file, (err, data) => { assert.ifError(err) assert.deepStrictEqual(obj, data) done() }) }) it('should resolve the promise with parsed JSON', (done) => { jf.readFile(file) .then(data => { assert.deepStrictEqual(data, obj) done() }) .catch(err => { assert.ifError(err) done() }) }) }) }) node-jsonfile-6.1.0/test/write-file-sync.test.js000066400000000000000000000073251374731337700216140ustar00rootroot00000000000000const assert = require('assert') const fs = require('fs') const os = require('os') const path = require('path') const rimraf = require('rimraf') const jf = require('../') /* global describe it beforeEach afterEach */ describe('+ writeFileSync()', () => { let TEST_DIR beforeEach((done) => { TEST_DIR = path.join(os.tmpdir(), 'jsonfile-tests-writefile-sync') rimraf.sync(TEST_DIR) fs.mkdir(TEST_DIR, done) }) afterEach((done) => { rimraf.sync(TEST_DIR) done() }) it('should serialize the JSON and write it to file', () => { const file = path.join(TEST_DIR, 'somefile4.json') const obj = { name: 'JP' } jf.writeFileSync(file, obj) const data = fs.readFileSync(file, 'utf8') const obj2 = JSON.parse(data) assert.strictEqual(obj2.name, obj.name) assert.strictEqual(data[data.length - 1], '\n') assert.strictEqual(data, '{"name":"JP"}\n') }) describe('> when JSON replacer is set', () => { it('should replace JSON', () => { const file = path.join(TEST_DIR, 'somefile.json') const sillyReplacer = function (k, v) { if (!(v instanceof RegExp)) return v return `regex:${v.toString()}` } const obj = { name: 'jp', reg: /hello/g } jf.writeFileSync(file, obj, { replacer: sillyReplacer }) const 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', () => { it('should write file with spaces', () => { const file = path.join(TEST_DIR, 'somefile.json') const obj = { name: 'JP' } jf.writeFileSync(file, obj, { spaces: 8 }) const data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, `${JSON.stringify(obj, null, 8)}\n`) }) it('should use EOL override', () => { const file = path.join(TEST_DIR, 'somefile.json') const obj = { name: 'JP' } jf.writeFileSync(file, obj, { spaces: 2, EOL: '***' }) const data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, '{*** "name": "JP"***}***') }) }) describe('> when passing encoding string as options', () => { it('should not error', () => { const file = path.join(TEST_DIR, 'somefile6.json') const obj = { name: 'jp' } jf.writeFileSync(file, obj, 'utf8') const data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, `${JSON.stringify(obj)}\n`) }) }) describe('> when EOF option is set to a falsey value', () => { beforeEach((done) => { TEST_DIR = path.join(os.tmpdir(), 'jsonfile-tests-writefile-sync') rimraf.sync(TEST_DIR) fs.mkdir(TEST_DIR, done) }) afterEach((done) => { rimraf.sync(TEST_DIR) done() }) it('should not have a the EOL symbol at the end of file', (done) => { const file = path.join(TEST_DIR, 'somefile2.json') const obj = { name: 'jp' } jf.writeFileSync(file, obj, { finalEOL: false }) const rawData = fs.readFileSync(file, 'utf8') const data = JSON.parse(rawData) assert.strictEqual(rawData[rawData.length - 1], '}') assert.strictEqual(data.name, obj.name) done() }) it('should have a the EOL symbol at the end of file when finalEOL is a truth value in options', (done) => { const file = path.join(TEST_DIR, 'somefile2.json') const obj = { name: 'jp' } jf.writeFileSync(file, obj, { finalEOL: true }) const rawData = fs.readFileSync(file, 'utf8') const data = JSON.parse(rawData) assert.strictEqual(rawData[rawData.length - 1], '\n') assert.strictEqual(data.name, obj.name) done() }) }) }) node-jsonfile-6.1.0/test/write-file.test.js000066400000000000000000000161721374731337700206420ustar00rootroot00000000000000const assert = require('assert') const fs = require('fs') const os = require('os') const path = require('path') const rimraf = require('rimraf') const jf = require('../') /* global describe it beforeEach afterEach */ describe('+ writeFile()', () => { let TEST_DIR beforeEach((done) => { TEST_DIR = path.join(os.tmpdir(), 'jsonfile-tests-writefile') rimraf.sync(TEST_DIR) fs.mkdir(TEST_DIR, done) }) afterEach((done) => { rimraf.sync(TEST_DIR) done() }) it('should serialize and write JSON', (done) => { const file = path.join(TEST_DIR, 'somefile2.json') const obj = { name: 'JP' } jf.writeFile(file, obj, (err) => { assert.ifError(err) fs.readFile(file, 'utf8', (err, data) => { assert.ifError(err) const obj2 = JSON.parse(data) assert.strictEqual(obj2.name, obj.name) // verify EOL assert.strictEqual(data[data.length - 1], '\n') done() }) }) }) it('should write JSON, resolve promise', (done) => { const file = path.join(TEST_DIR, 'somefile2.json') const obj = { name: 'JP' } jf.writeFile(file, obj) .then(res => { fs.readFile(file, 'utf8', (err, data) => { assert.ifError(err) const obj2 = JSON.parse(data) assert.strictEqual(obj2.name, obj.name) // verify EOL assert.strictEqual(data[data.length - 1], '\n') done() }) }) .catch(err => { assert.ifError(err) done() }) }) describe('> when JSON replacer is set', () => { let file, sillyReplacer, obj beforeEach((done) => { file = path.join(TEST_DIR, 'somefile.json') sillyReplacer = function (k, v) { if (!(v instanceof RegExp)) return v return `regex:${v.toString()}` } obj = { name: 'jp', reg: /hello/g } done() }) it('should replace JSON', (done) => { jf.writeFile(file, obj, { replacer: sillyReplacer }, (err) => { assert.ifError(err) const 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() }) }) it('should replace JSON, resolve promise', (done) => { jf.writeFile(file, obj, { replacer: sillyReplacer }) .then(res => { const 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() }) .catch(err => { assert.ifError(err) done() }) }) }) describe('> when spaces passed as an option', () => { let file, obj beforeEach((done) => { file = path.join(TEST_DIR, 'somefile.json') obj = { name: 'jp' } done() }) it('should write file with spaces', (done) => { jf.writeFile(file, obj, { spaces: 8 }, (err) => { assert.ifError(err) const data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, `${JSON.stringify(obj, null, 8)}\n`) done() }) }) it('should write file with spaces, resolve the promise', (done) => { jf.writeFile(file, obj, { spaces: 8 }) .then(res => { const data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, `${JSON.stringify(obj, null, 8)}\n`) done() }) .catch(err => { assert.ifError(err) done() }) }) }) describe('> when spaces, EOL are passed as options', () => { let file, obj beforeEach((done) => { file = path.join(TEST_DIR, 'somefile.json') obj = { name: 'jp' } done() }) it('should use EOL override', (done) => { jf.writeFile(file, obj, { spaces: 2, EOL: '***' }, (err) => { assert.ifError(err) const data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, '{*** "name": "jp"***}***') done() }) }) it('should use EOL override, resolve the promise', (done) => { jf.writeFile(file, obj, { spaces: 2, EOL: '***' }) .then(res => { const data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, '{*** "name": "jp"***}***') done() }) .catch(err => { assert.ifError(err) done() }) }) }) describe('> when passing encoding string as options', () => { let file, obj beforeEach((done) => { file = path.join(TEST_DIR, 'somefile.json') obj = { name: 'jp' } done() }) it('should not error', (done) => { jf.writeFile(file, obj, 'utf8', (err) => { assert.ifError(err) const data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, `${JSON.stringify(obj)}\n`) done() }) }) it('should not error, resolve the promise', (done) => { jf.writeFile(file, obj, 'utf8') .then(res => { const data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, `${JSON.stringify(obj)}\n`) done() }) .catch(err => { assert.ifError(err) done() }) }) }) describe('> when EOF option is set to a falsey value', () => { beforeEach((done) => { TEST_DIR = path.join(os.tmpdir(), 'jsonfile-tests-writefile') rimraf.sync(TEST_DIR) fs.mkdir(TEST_DIR, done) }) afterEach((done) => { rimraf.sync(TEST_DIR) done() }) it('should not have a the EOL symbol at the end of file', (done) => { const file = path.join(TEST_DIR, 'somefile2.json') const obj = { name: 'jp' } jf.writeFile(file, obj, { finalEOL: false }, (err) => { assert.ifError(err) fs.readFile(file, 'utf8', (_, rawData) => { const data = JSON.parse(rawData) assert.strictEqual(rawData[rawData.length - 1], '}') assert.strictEqual(data.name, obj.name) done() }) }) }) it('should have a the EOL symbol at the end of file when finalEOL is a truth value in options', (done) => { const file = path.join(TEST_DIR, 'somefile2.json') const obj = { name: 'jp' } jf.writeFile(file, obj, { finalEOL: true }, (err) => { assert.ifError(err) fs.readFile(file, 'utf8', (_, rawData) => { const data = JSON.parse(rawData) assert.strictEqual(rawData[rawData.length - 1], '\n') assert.strictEqual(data.name, obj.name) done() }) }) }) }) // Prevent https://github.com/jprichardson/node-jsonfile/issues/81 from happening describe("> when callback isn't passed & can't serialize", () => { it('should not write an empty file, should reject the promise', function (done) { this.slow(1100) const file = path.join(TEST_DIR, 'somefile.json') const obj1 = { name: 'JP' } const obj2 = { person: obj1 } obj1.circular = obj2 jf.writeFile(file, obj1) .catch(err => { assert(err) assert(!fs.existsSync(file)) done() }) }) }) }) node-jsonfile-6.1.0/utils.js000066400000000000000000000007621374731337700157740ustar00rootroot00000000000000function stringify (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) { const EOF = finalEOL ? EOL : '' const str = JSON.stringify(obj, replacer, spaces) return str.replace(/\n/g, EOL) + EOF } 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') return content.replace(/^\uFEFF/, '') } module.exports = { stringify, stripBom }