write.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict'
  2. const fs = require('fs')
  3. const promise = require('./promise')
  4. const streamify = require('./streamify')
  5. module.exports = write
  6. /**
  7. * Public function `write`.
  8. *
  9. * Returns a promise and asynchronously serialises a data structure to a
  10. * JSON file on disk. Sanely handles promises, buffers, maps and other
  11. * iterables.
  12. *
  13. * @param path: Path to the JSON file.
  14. *
  15. * @param data: The data to transform.
  16. *
  17. * @option space: Indentation string, or the number of spaces
  18. * to indent each nested level by.
  19. *
  20. * @option promises: 'resolve' or 'ignore', default is 'resolve'.
  21. *
  22. * @option buffers: 'toString' or 'ignore', default is 'toString'.
  23. *
  24. * @option maps: 'object' or 'ignore', default is 'object'.
  25. *
  26. * @option iterables: 'array' or 'ignore', default is 'array'.
  27. *
  28. * @option circular: 'error' or 'ignore', default is 'error'.
  29. *
  30. * @option yieldRate: The number of data items to process per timeslice,
  31. * default is 16384.
  32. *
  33. * @option bufferLength: The length of the buffer, default is 1024.
  34. *
  35. * @option highWaterMark: If set, will be passed to the readable stream constructor
  36. * as the value for the highWaterMark option.
  37. *
  38. * @option Promise: The promise constructor to use, defaults to bluebird.
  39. **/
  40. function write (path, data, options) {
  41. const Promise = promise(options)
  42. return new Promise((resolve, reject) => {
  43. streamify(data, options)
  44. .pipe(fs.createWriteStream(path, options))
  45. .on('finish', () => {
  46. resolve()
  47. })
  48. .on('error', reject)
  49. .on('dataError', reject)
  50. })
  51. }