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