index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict';
  2. const {promisify} = require('util');
  3. const path = require('path');
  4. const fs = require('graceful-fs');
  5. const writeFileAtomic = require('write-file-atomic');
  6. const sortKeys = require('sort-keys');
  7. const makeDir = require('make-dir');
  8. const detectIndent = require('detect-indent');
  9. const isPlainObj = require('is-plain-obj');
  10. const readFile = promisify(fs.readFile);
  11. const init = (fn, filePath, data, options) => {
  12. if (!filePath) {
  13. throw new TypeError('Expected a filepath');
  14. }
  15. if (data === undefined) {
  16. throw new TypeError('Expected data to stringify');
  17. }
  18. options = {
  19. indent: '\t',
  20. sortKeys: false,
  21. ...options
  22. };
  23. if (options.sortKeys && isPlainObj(data)) {
  24. data = sortKeys(data, {
  25. deep: true,
  26. compare: typeof options.sortKeys === 'function' ? options.sortKeys : undefined
  27. });
  28. }
  29. return fn(filePath, data, options);
  30. };
  31. const main = async (filePath, data, options) => {
  32. let {indent} = options;
  33. let trailingNewline = '\n';
  34. try {
  35. const file = await readFile(filePath, 'utf8');
  36. if (!file.endsWith('\n')) {
  37. trailingNewline = '';
  38. }
  39. if (options.detectIndent) {
  40. indent = detectIndent(file).indent;
  41. }
  42. } catch (error) {
  43. if (error.code !== 'ENOENT') {
  44. throw error;
  45. }
  46. }
  47. const json = JSON.stringify(data, options.replacer, indent);
  48. return writeFileAtomic(filePath, `${json}${trailingNewline}`, {mode: options.mode, chown: false});
  49. };
  50. const mainSync = (filePath, data, options) => {
  51. let {indent} = options;
  52. let trailingNewline = '\n';
  53. try {
  54. const file = fs.readFileSync(filePath, 'utf8');
  55. if (!file.endsWith('\n')) {
  56. trailingNewline = '';
  57. }
  58. if (options.detectIndent) {
  59. indent = detectIndent(file).indent;
  60. }
  61. } catch (error) {
  62. if (error.code !== 'ENOENT') {
  63. throw error;
  64. }
  65. }
  66. const json = JSON.stringify(data, options.replacer, indent);
  67. return writeFileAtomic.sync(filePath, `${json}${trailingNewline}`, {mode: options.mode, chown: false});
  68. };
  69. module.exports = async (filePath, data, options) => {
  70. await makeDir(path.dirname(filePath), {fs});
  71. return init(main, filePath, data, options);
  72. };
  73. module.exports.sync = (filePath, data, options) => {
  74. makeDir.sync(path.dirname(filePath), {fs});
  75. init(mainSync, filePath, data, options);
  76. };