diff --git a/doc/api/util.markdown b/doc/api/util.markdown index 0f2aa107302c29..5249158bea00b0 100644 --- a/doc/api/util.markdown +++ b/doc/api/util.markdown @@ -477,6 +477,19 @@ when the deprecated API is used. Configurable at run-time through the `process.throwDeprecation` takes precedence over `process.traceDeprecation`. +## util.guessHandleType(fd) + +Returns the assumed handle type for the given `fd`. + +Possible values include: + +* `'FILE'` +* `'TTY'` +* `'PIPE'` +* `'TCP'` +* `'UNKNOWN'` + + ## util.debug(string) Stability: 0 - Deprecated: use console.error() instead. diff --git a/lib/util.js b/lib/util.js index c5d7bea7db352d..7d2121e1f33c39 100644 --- a/lib/util.js +++ b/lib/util.js @@ -4,6 +4,7 @@ const uv = process.binding('uv'); const Buffer = require('buffer').Buffer; const internalUtil = require('internal/util'); var Debug; +var TTYWrap; const formatRegExp = /%[sdj%]/g; exports.format = function(f) { @@ -864,3 +865,16 @@ exports._exceptionWithHostPort = function(err, } return ex; }; + +exports.guessHandleType = function(fd) { + if (!TTYWrap) + TTYWrap = process.binding('tty_wrap'); + + if (typeof fd !== 'number') + throw new TypeError('fd must be a number'); + + if (fd < 0) + throw new Error('fd cannot be less than 0'); + + return TTYWrap.guessHandleType(fd); +}; diff --git a/test/sequential/test-util-guess-handle-type.js b/test/sequential/test-util-guess-handle-type.js new file mode 100644 index 00000000000000..4a5cdaabf8466e --- /dev/null +++ b/test/sequential/test-util-guess-handle-type.js @@ -0,0 +1,47 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const util = require('util'); +const fs = require('fs'); +const path = require('path'); +const net = require('net'); + +// Throw on non-numeric fd +assert.throws(function() { + util.guessHandleType('test'); +}, /fd must be a number/); + +// Throw on fd < 0 +assert.throws(function() { + util.guessHandleType(-1); +}, /fd cannot be less than 0/); + +// Check for FILE handle type +const filename = path.join(common.tmpDir, 'guess-handle'); +common.refreshTmpDir(); +fs.writeFileSync(filename, '', 'utf8'); +const fd = fs.openSync(filename, 'r+'); +assert.strictEqual(util.guessHandleType(fd), 'FILE'); +fs.closeSync(fd); +fs.unlinkSync(filename); + +// Check for TTY handle type +assert.strictEqual(util.guessHandleType(process.stdin.fd), 'TTY'); + +// Check for PIPE handle type +var server = net.createServer(assert.fail); +server.listen(common.PIPE, function() { + assert.strictEqual(util.guessHandleType(server._handle.fd), 'PIPE'); + server.close(); +}); + +// Check for TCP handle type +var server2 = net.createServer(assert.fail); +server2.listen(common.util, function() { + assert.strictEqual(util.guessHandleType(server2._handle.fd), 'TCP'); + server2.close(); +}); + +// Check for UNKNOWN handle type +assert.strictEqual(util.guessHandleType(123456), 'UNKNOWN');