better option parsing for socket.write()

pull/5370/head
Ryan Dahl 2010-12-15 15:15:27 -08:00
parent 1dad95a3a9
commit c970968ee6
3 changed files with 38 additions and 6 deletions

View File

@ -196,16 +196,22 @@ context of the defined or default list of trusted CA certificates.
Returns a JSON structure detailing the peer's certificate, containing a dictionary
with keys for the certificate `'subject'`, `'issuer'`, `'valid_from'` and `'valid_to'`.
#### stream.write(data, encoding='ascii')
#### stream.write(data, [encoding])
Sends data on the stream. The second parameter specifies the encoding in
the case of a string--it defaults to ASCII because encoding to UTF8 is rather
slow.
Sends data on the stream. The second parameter specifies the encoding in the
case of a string--it defaults to UTF8 encoding.
Returns `true` if the entire data was flushed successfully to the kernel
buffer. Returns `false` if all or part of the data was queued in user memory.
`'drain'` will be emitted when the buffer is again free.
#### stream.write(data, [encoding], [fileDescriptor])
For UNIX sockets, it is possible to send a file descriptor through the
stream. Simply add the `fileDescriptor` argument and listen for the `'fd'`
event on the other end.
#### stream.end([data], [encoding])
Half-closes the stream. I.E., it sends a FIN packet. It is possible the

View File

@ -264,7 +264,33 @@ Object.defineProperty(Stream.prototype, 'readyState', {
// Returns true if all the data was flushed to socket. Returns false if
// something was queued. If data was queued, then the 'drain' event will
// signal when it has been finally flushed to socket.
Stream.prototype.write = function(data, encoding, fd) {
Stream.prototype.write = function(data /* [encoding], [fd], [cb] */) {
var encoding, fd, cb;
// parse arguments
if (typeof arguments[1] == 'string') {
encoding = arguments[1];
if (typeof arguments[2] == 'number') {
fd = arguments[2];
cb = arguments[3];
} else {
cb = arguments[2];
}
} else if (typeof arguments[1] == 'number') {
fd = arguments[1];
cb = arguments[2];
} else if (typeof arguments[2] == 'number') {
// This case is to support old calls when the encoding argument
// was not optional: s.write(buf, undefined, pipeFDs[1])
encoding = arguments[1];
fd = arguments[2];
cb = arguments[3];
} else {
cb = arguments[1];
}
// TODO - actually use cb
if (this._connecting || (this._writeQueue && this._writeQueue.length)) {
if (!this._writeQueue) {
this._writeQueue = [];

View File

@ -94,7 +94,7 @@ var srv = net.createServer(function(s) {
buf.write(JSON.stringify(DATA) + '\n', 'utf8');
s.write(str, 'utf8', pipeFDs[1]);
if (s.write(buf, undefined, pipeFDs[1])) {
if (s.write(buf, pipeFDs[1])) {
netBinding.close(pipeFDs[1]);
} else {
s.addListener('drain', function() {