UNPKG

2.7 kBMarkdownView Raw
1# wrote
2
3[![npm version](https://badge.fury.io/js/wrote.svg)](https://badge.fury.io/js/wrote)
4
5Promise-based write for Node.js
6
7## `wrote(filepath?:String) => Promise<Writable> (ws.writable == true)`
8
9Create a write stream to your file without hastle.
10
11```js
12const Writable = require('stream').Writable
13const path = require('path')
14const wrote = require('./')
15const HOME_DIR = require('os').homedir()
16
17const file = path.join(HOME_DIR, `wrote-${Math.floor(Math.random() * 1e5)}.data`)
18
19return wrote(file)
20 .then((ws) => {
21 console.log(ws instanceof Writable) // true
22 console.log(ws.path) // ~/wrote-35558.data
23 })
24 .catch(console.error)
25
26```
27
28If you don't have a file, a new one in the temp directory will be created for you.
29
30```js
31const wrote = require('wrote')
32const Writable = require('stream').Writable
33
34return wrote()
35 .then((ws) => {
36 console.log(ws instanceof Writable) // true
37 console.log(ws.path) // /var/folders/s0/l33t/T/wrote-35558.data
38 })
39 .catch(console.error)
40```
41
42## `wrote.erase(ws:Writable) => Promise<Writable> (ws.writable == false)`
43
44Erase file and close stream.
45
46```js
47const wrote = require('wrote')
48const Writable = require('stream').Writable
49const path = require('path')
50const HOME_DIR = require('os').homedir()
51const fs = require('fs')
52
53const file = path.join(HOME_DIR, `wrote-${Math.floor(Math.random() * 1e5)}.data`)
54
55return wrote(file)
56 .then((ws) => {
57 console.log(ws instanceof Writable) // true
58 console.log(ws.writable) // true
59 console.log(ws.path) // ~/wrote-35558.data
60 return wrote.erase(ws)
61 })
62 .then((ws) => {
63 console.log(ws.path) // ~/wrote-35558.data, but no longer exists
64 console.log(ws.writable) // false
65 })
66 .catch(console.error)
67```
68
69## wrote.write(ws:Writable, data:any|Readable) => Promise<Writable>
70
71Pipe a `Readable` to the `Writable` stream and wait until it is finished, or end `Writable` with
72given data (pass `null` to end stream without any more data).
73
74```js
75const wrote = require('wrote')
76const assert = require('assert')
77const Writable = require('stream').Writable
78
79const testString = 'hello world'
80const buffer = Buffer.from(testString)
81const allRawData = []
82const ws = new Writable({
83 write: (chunk, encoding, next) => {
84 allRawData.push(chunk)
85 next()
86 },
87})
88wrote.write(ws, buffer)
89 .then(() => {
90 console.log(allRawData.map(d => String(d))) // [ 'hello world' ]
91 assert.deepEqual(allRawData, [
92 buffer,
93 ])
94 })
95 .catch(console.error)
96```
97
98## todo
99
100- pass options to `fs.createWriteStream`
101
102---
103
104Licence: MIT
105
106*(c) [Sobesednik-Media](https://sobesednik.media) 2017*