From 1fb702cb373f2e7fd78f2f4a75b95279aa98f88d Mon Sep 17 00:00:00 2001 From: Bryan English Date: Sat, 23 Sep 2017 01:40:35 -0700 Subject: [PATCH] tty,doc: add type-check to isatty Previously, various inputs other than non-negative integers would produce incorrect results. Added type-checking on input, returning false for anything other than non-negative integers. Also clarified in docs. PR-URL: https://github.com/nodejs/node/pull/15567 Reviewed-By: Luigi Pinca Reviewed-By: Ruben Bridgewater Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Jeremiah Senkpiel --- doc/api/tty.md | 3 ++- lib/tty.js | 2 +- test/pseudo-tty/test-tty-isatty.js | 17 +++++++++++++++++ test/pseudo-tty/test-tty-isatty.out | 0 4 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 test/pseudo-tty/test-tty-isatty.js create mode 100644 test/pseudo-tty/test-tty-isatty.out diff --git a/doc/api/tty.md b/doc/api/tty.md index 2950eb6db1a396..baa31ac8f0be7c 100644 --- a/doc/api/tty.md +++ b/doc/api/tty.md @@ -123,4 +123,5 @@ added: v0.5.8 * `fd` {number} A numeric file descriptor The `tty.isatty()` method returns `true` if the given `fd` is associated with -a TTY and `false` if is not. +a TTY and `false` if it is not, including whenever `fd` is not a non-negative +integer. diff --git a/lib/tty.js b/lib/tty.js index 08977115c6e60d..b9c829066d5f00 100644 --- a/lib/tty.js +++ b/lib/tty.js @@ -10,7 +10,7 @@ const readline = require('readline'); exports.isatty = function(fd) { - return isTTY(fd); + return Number.isInteger(fd) && fd >= 0 && isTTY(fd); }; diff --git a/test/pseudo-tty/test-tty-isatty.js b/test/pseudo-tty/test-tty-isatty.js new file mode 100644 index 00000000000000..3a7b2940311221 --- /dev/null +++ b/test/pseudo-tty/test-tty-isatty.js @@ -0,0 +1,17 @@ +'use strict'; + +require('../common'); +const { strictEqual } = require('assert'); +const { isatty } = require('tty'); + +strictEqual(isatty(0), true, 'stdin reported to not be a tty, but it is'); +strictEqual(isatty(1), true, 'stdout reported to not be a tty, but it is'); +strictEqual(isatty(2), true, 'stderr reported to not be a tty, but it is'); + +strictEqual(isatty(-1), false, '-1 reported to be a tty, but it is not'); +strictEqual(isatty(55555), false, '55555 reported to be a tty, but it is not'); +strictEqual(isatty(1.1), false, '1.1 reported to be a tty, but it is not'); +strictEqual(isatty('1'), false, '\'1\' reported to be a tty, but it is not'); +strictEqual(isatty({}), false, '{} reported to be a tty, but it is not'); +strictEqual(isatty(() => {}), false, + '() => {} reported to be a tty, but it is not'); diff --git a/test/pseudo-tty/test-tty-isatty.out b/test/pseudo-tty/test-tty-isatty.out new file mode 100644 index 00000000000000..e69de29bb2d1d6