aboutsummaryrefslogtreecommitdiffstats
path: root/vnfmarket/src/main/webapp/vnfmarket/node_modules/fs-extra/lib/streams/create-output-stream.js
blob: e6db2dd80c2bac9b4b72c7556eb87dc631111576 (plain)
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