-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
93 lines (77 loc) · 2.17 KB
/
index.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
var util = require('util'),
fs = require('fs'),
stream = require('stream'),
Writable = stream.Writable,
constants = fs.constants;
var O_NONBLOCK = constants.O_NONBLOCK ,
S_IFIFO = constants.S_IFIFO,
O_WRONLY = constants.O_WRONLY;
/**
* @constructor
* @class WriteStream
* @augments stream.Writable
* @param {String} path FIFO object file path
* @param {Object} [options] @see {@link http://nodejs.org/api/stream.html common writable stream options}
* @returns {WriteStream}
*/
function WriteStream(path, options) {
Writable.call(this, options);
this.path = path;
this.fstream = null;
setImmediate(this.init.bind(this));
}
util.inherits(WriteStream, Writable);
function isFIFOWritable(path) {
try {
var fd = fs.openSync(path, O_WRONLY | O_NONBLOCK, S_IFIFO);
fs.closeSync(fd);
} catch(e) {
return false;
}
return true;
}
/**
* Try to initialize underlying fs.WriteStream
* @fires WriteStream#nofifo
*/
WriteStream.prototype.init = function() {
if (this.fstream !== null) {
return;
}
if ( ! isFIFOWritable(this.path)) {
this.emit('nofifo', this.path);
return;
}
var self = this;
this.fstream = fs.createWriteStream(this.path, { flags: O_WRONLY, mode: S_IFIFO });
this.fstream.on('error', function(error) {
self.fstream = null;
if (error.code === 'EPIPE') {
self.emit('nofifo', self.path, error);
} else {
self.emit('error', error);
}
});
this.fstream.on('finish', function() {
self.fstream = null;
self.emit('finish');
});
this.fstream.on('drain', this.emit.bind(this, 'drain'));
this.emit('drain');
};
/**
* @see {@link http://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback_1}
* @private
*/
WriteStream.prototype._write = function(chunk, encoding, callback) {
if (this.fstream === null) {
setImmediate(callback);
return false;
} else {
return this.fstream.write(chunk, encoding, callback);
}
};
exports.WriteStream = WriteStream;
exports.createWriteStream = function(path) {
return new WriteStream(path);
};