UNPKG

9.46 kBMarkdownView Raw
1# write [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/write.svg?style=flat)](https://www.npmjs.com/package/write) [![NPM monthly downloads](https://img.shields.io/npm/dm/write.svg?style=flat)](https://npmjs.org/package/write) [![NPM total downloads](https://img.shields.io/npm/dt/write.svg?style=flat)](https://npmjs.org/package/write) [![Build Status](https://travis-ci.org/jonschlinkert/write.svg?branch=master)](https://travis-ci.org/jonschlinkert/write)
2
3> Write data to a file, replacing the file if it already exists and creating any intermediate directories if they don't already exist. Thin wrapper around node's native fs methods.
4
5Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
6
7## Install
8
9Install with [npm](https://www.npmjs.com/) (requires [Node.js](https://nodejs.org/en/) >=10):
10
11```sh
12$ npm install --save write
13```
14
15## Usage
16
17```js
18const write = require('write');
19```
20
21## Options
22
23The following options may be used with any method.
24
25### options.newline
26
27**Type**: `boolean`
28
29**Default**: `undefined`
30
31Ensure that contents has a trailing newline before writing it to the file system.
32
33```js
34write.sync('foo.txt', 'some data...', { newline: true });
35```
36
37### options.overwrite
38
39**Type**: `boolean`
40
41**Default**: `undefined`
42
43Set to `false` to prevent existing files from being overwritten. See [increment](#optionsincrement) for a less severe alternative.
44
45```js
46write.sync('foo.txt', 'some data...', { overwrite: false });
47```
48
49### options.increment
50
51**Type**: `boolean`
52
53**Default**: `undefined`
54
55Set to `true` to automatically rename files by appending an increment, like `foo (2).txt`, to prevent `foo.txt` from being overwritten. This is useful when writing log files, or other information where the file name is less important than the contents being written.
56
57```js
58write.sync('foo.txt', 'some data...', { increment: true });
59// if "foo.txt" exists, the file will be renamed to "foo (2).txt"
60```
61
62## API
63
64### [write](index.js#L41)
65
66Asynchronously writes data to a file, replacing the file if it already exists and creating any intermediate directories if they don't already exist. Data can be a string or a buffer. Returns a promise if a callback function is not passed.
67
68**Params**
69
70* `filepath` **{String}**: file path.
71* `data` **{String|Buffer|Uint8Array}**: Data to write.
72* `options` **{Object}**: Options to pass to [fs.writeFile](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback)
73* `callback` **{Function}**: (optional) If no callback is provided, a promise is returned.
74* `returns` **{Object}**: Returns an object with the `path` and `contents` of the file that was written to the file system. This is useful for debugging when `options.increment` is used and the path might have been modified.
75
76**Example**
77
78```js
79const write = require('write');
80
81// async/await
82(async () => {
83 await write('foo.txt', 'This is content...');
84})();
85
86// promise
87write('foo.txt', 'This is content...')
88 .then(() => {
89 // do stuff
90 });
91
92// callback
93write('foo.txt', 'This is content...', err => {
94 // do stuff with err
95});
96```
97
98### [.sync](index.js#L88)
99
100The synchronous version of [write](#write). Returns undefined.
101
102**Params**
103
104* `filepath` **{String}**: file path.
105* `data` **{String|Buffer|Uint8Array}**: Data to write.
106* `options` **{Object}**: Options to pass to [fs.writeFileSync](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options)
107* `returns` **{Object}**: Returns an object with the `path` and `contents` of the file that was written to the file system. This is useful for debugging when `options.increment` is used and the path might have been modified.
108
109**Example**
110
111```js
112const write = require('write');
113write.sync('foo.txt', 'This is content...');
114```
115
116### [.stream](index.js#L127)
117
118Returns a new [WriteStream](https://nodejs.org/api/fs.html#fs_class_fs_writestream) object. Uses `fs.createWriteStream` to write data to a file, replacing the file if it already exists and creating any intermediate directories if they don't already exist. Data can be a string or a buffer.
119
120**Params**
121
122* `filepath` **{String}**: file path.
123* `options` **{Object}**: Options to pass to [fs.createWriteStream](https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options)
124* `returns` **{Stream}**: Returns a new [WriteStream](https://nodejs.org/api/fs.html#fs_class_fs_writestream) object. (See [Writable Stream](https://nodejs.org/api/stream.html#stream_class_stream_writable)).
125
126**Example**
127
128```js
129const fs = require('fs');
130const write = require('write');
131fs.createReadStream('README.md')
132 .pipe(write.stream('a/b/c/other-file.md'))
133 .on('close', () => {
134 // do stuff
135 });
136```
137
138## Release history
139
140See [CHANGELOG.md].
141
142## About
143
144<details>
145<summary><strong>Contributing</strong></summary>
146
147Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
148
149</details>
150
151<details>
152<summary><strong>Running Tests</strong></summary>
153
154Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
155
156```sh
157$ npm install && npm test
158```
159
160</details>
161
162<details>
163<summary><strong>Building docs</strong></summary>
164
165_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
166
167To generate the readme, run the following command:
168
169```sh
170$ npm install -g verbose/verb#dev verb-generate-readme && verb
171```
172
173</details>
174
175### Related projects
176
177You might also be interested in these projects:
178
179* [add-filename-increment](https://www.npmjs.com/package/add-filename-increment): When copying or moving files, it's common for operating systems to automatically add an increment… [more](https://github.com/jonschlinkert/add-filename-increment) | [homepage](https://github.com/jonschlinkert/add-filename-increment "When copying or moving files, it's common for operating systems to automatically add an increment or 'copy' to duplicate file names. This does that for Node.js applications, with automatic platform detection and support for Linux, MacOs, and Windows conve")
180* [delete](https://www.npmjs.com/package/delete): Delete files and folders and any intermediate directories if they exist (sync and async). | [homepage](https://github.com/jonschlinkert/delete "Delete files and folders and any intermediate directories if they exist (sync and async).")
181* [read-data](https://www.npmjs.com/package/read-data): Read JSON or YAML files. | [homepage](https://github.com/jonschlinkert/read-data "Read JSON or YAML files.")
182* [read-yaml](https://www.npmjs.com/package/read-yaml): Very thin wrapper around js-yaml for directly reading in YAML files. | [homepage](https://github.com/jonschlinkert/read-yaml "Very thin wrapper around js-yaml for directly reading in YAML files.")
183* [strip-filename-increment](https://www.npmjs.com/package/strip-filename-increment): Operating systems commonly add a trailing increment, or the word 'copy', or something similar to… [more](https://github.com/jonschlinkert/strip-filename-increment) | [homepage](https://github.com/jonschlinkert/strip-filename-increment "Operating systems commonly add a trailing increment, or the word 'copy', or something similar to duplicate files. This strips those increments. Tested on Windows, MacOS, and Linux.")
184* [write-data](https://www.npmjs.com/package/write-data): Write a YAML or JSON file to disk. Automatically detects the format to write based… [more](https://github.com/jonschlinkert/write-data) | [homepage](https://github.com/jonschlinkert/write-data "Write a YAML or JSON file to disk. Automatically detects the format to write based on extension. Or pass `ext` on the options.")
185* [write-json](https://www.npmjs.com/package/write-json): Write a JSON file to disk, also creates intermediate directories in the destination path if… [more](https://github.com/jonschlinkert/write-json) | [homepage](https://github.com/jonschlinkert/write-json "Write a JSON file to disk, also creates intermediate directories in the destination path if they don't already exist.")
186* [write-yaml](https://www.npmjs.com/package/write-yaml): Write YAML. Converts JSON to YAML writes it to the specified file. | [homepage](https://github.com/jonschlinkert/write-yaml "Write YAML. Converts JSON to YAML writes it to the specified file.")
187
188### Contributors
189
190| **Commits** | **Contributor** |
191| --- | --- |
192| 42 | [jonschlinkert](https://github.com/jonschlinkert) |
193| 2 | [jpetitcolas](https://github.com/jpetitcolas) |
194| 1 | [tunnckoCore](https://github.com/tunnckoCore) |
195
196### Author
197
198**Jon Schlinkert**
199
200* [GitHub Profile](https://github.com/jonschlinkert)
201* [Twitter Profile](https://twitter.com/jonschlinkert)
202* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
203
204### License
205
206Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert).
207Released under the [MIT License](LICENSE).
208
209***
210
211_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on September 04, 2019._
\No newline at end of file