1 | const fs = require('fs')
|
2 | const os = require('os')
|
3 | const path = require('path')
|
4 | const Readable = require('stream').Readable
|
5 | const Writable = require('stream').Writable
|
6 | const makePromise = require('makepromise')
|
7 | const TEMP_DIR = os.tmpdir()
|
8 |
|
9 | function openFileForWrite(filepath) {
|
10 | return new Promise((resolve, reject) => {
|
11 | const ws = fs.createWriteStream(filepath, {
|
12 | flags: 'w',
|
13 | defaultEncoding: 'utf8',
|
14 | fd: null,
|
15 | mode: 0o666,
|
16 | autoClose: true,
|
17 | })
|
18 | ws.once('open', () => resolve(ws))
|
19 | ws.once('error', reject)
|
20 | })
|
21 | }
|
22 |
|
23 | function getTempFile() {
|
24 | const rnd = Math.ceil(Math.random() * 100000)
|
25 | const tempFile = path.join(TEMP_DIR, `wrote-${rnd}.data`)
|
26 | return tempFile
|
27 | }
|
28 |
|
29 | function unlink(path) {
|
30 | const promise = makePromise(fs.unlink, path, path)
|
31 | return promise
|
32 | }
|
33 |
|
34 | function endStream(ws) {
|
35 | if (!ws.writable || ws.closed) {
|
36 | return Promise.reject(new Error('stream should be writable'))
|
37 | }
|
38 | const promise = new Promise((resolve, reject) => {
|
39 | ws.once('close', () => resolve(ws))
|
40 | ws.once('error', reject)
|
41 | })
|
42 | return makePromise(ws.close.bind(ws))
|
43 | .then(() => promise)
|
44 | }
|
45 |
|
46 | function erase(ws) {
|
47 | return unlink(ws.path)
|
48 | .then(() => {
|
49 | if (!ws.closed) {
|
50 | return endStream(ws)
|
51 | }
|
52 | return ws
|
53 | })
|
54 | }
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 | function wrote(file) {
|
62 | const _file = (typeof file).toLowerCase() === 'string' ?
|
63 | file : getTempFile()
|
64 | return openFileForWrite(_file)
|
65 | }
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | function write(ws, source) {
|
75 | if (!(ws instanceof Writable)) {
|
76 | return Promise.reject(new Error('Writable stream expected'))
|
77 | }
|
78 | if (source instanceof Readable) {
|
79 | if (!source.readable) {
|
80 | return Promise.reject(new Error('Stream is not readable'))
|
81 | }
|
82 | return new Promise((resolve, reject) => {
|
83 | ws.on('finish', () => {
|
84 | resolve(ws)
|
85 | })
|
86 | ws.on('error', reject)
|
87 | source.on('error', reject)
|
88 | source.pipe(ws)
|
89 | })
|
90 | }
|
91 | return makePromise(ws.end.bind(ws), source, ws)
|
92 | }
|
93 |
|
94 | Object.defineProperty(wrote, 'write', { get: () => write })
|
95 | Object.defineProperty(wrote, 'erase', { get: () => erase })
|
96 |
|
97 | module.exports = wrote
|