create-output-stream.js
960 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
var path = require('path')
var fs = require('fs')
var mkdir = require('../mkdirs')
var WriteStream = fs.WriteStream
function createOutputStream (file, options) {
var dirExists = false
var dir = path.dirname(file)
options = options || {}
// if fd is set with an actual number, file is created, hence directory is too
if (options.fd) {
return fs.createWriteStream(file, options)
} else {
// this hacks the WriteStream constructor from calling open()
options.fd = -1
}
var ws = new WriteStream(file, options)
var oldOpen = ws.open
ws.open = function () {
ws.fd = null // set actual fd
if (dirExists) return oldOpen.call(ws)
// this only runs once on first write
mkdir.mkdirs(dir, function (err) {
if (err) {
ws.destroy()
ws.emit('error', err)
return
}
dirExists = true
oldOpen.call(ws)
})
}
ws.open()
return ws
}
module.exports = createOutputStream