1 | fs = require 'fs'
|
2 | path = require 'path'
|
3 | events = require 'events'
|
4 | os = require 'options-stream'
|
5 |
|
6 | class FileStream extends events.EventEmitter
|
7 | constructor : (options)->
|
8 | @options = os
|
9 | filePath : ''
|
10 |
|
11 | bufferLength : 0
|
12 | mode : '0664'
|
13 | , options
|
14 |
|
15 | @_buffer = []
|
16 |
|
17 | @_newStream()
|
18 |
|
19 | write : (str)->
|
20 | @_buffer.push str
|
21 | @flush() if @_buffer.length > @options.bufferLength
|
22 |
|
23 | end : ()->
|
24 | return unless @stream
|
25 | @_closeStream()
|
26 |
|
27 | _newStream : ->
|
28 | {filePath, mode} = @options
|
29 |
|
30 | stream = fs.createWriteStream filePath, flags: 'a', mode: mode
|
31 | stream.on 'error', @emit.bind @, 'error'
|
32 | stream.on 'open', @emit.bind @, 'open'
|
33 | stream.on 'close', @emit.bind @, 'close'
|
34 | @stream = stream
|
35 |
|
36 | _closeStream : ->
|
37 | @flush()
|
38 | @stream.end()
|
39 | @stream.destroySoon()
|
40 | @stream = null
|
41 |
|
42 | flush : ->
|
43 | return unless @_buffer.length
|
44 | @stream.write @_buffer.join ''
|
45 | @_buffer.length = 0
|
46 |
|
47 | module.exports = (options)->
|
48 | new FileStream options
|