doc: improvements to console.markdown copy
[platform/upstream/nodejs.git] / lib / tty.js
1 'use strict';
2
3 const util = require('util');
4 const internalUtil = require('internal/util');
5 const net = require('net');
6 const TTY = process.binding('tty_wrap').TTY;
7 const isTTY = process.binding('tty_wrap').isTTY;
8 const inherits = util.inherits;
9 const errnoException = util._errnoException;
10
11
12 exports.isatty = function(fd) {
13   return isTTY(fd);
14 };
15
16
17 // backwards-compat
18 exports.setRawMode = internalUtil.deprecate(function(flag) {
19   if (!process.stdin.isTTY) {
20     throw new Error('can\'t set raw mode on non-tty');
21   }
22   process.stdin.setRawMode(flag);
23 }, 'tty.setRawMode is deprecated. ' +
24    'Use process.stdin.setRawMode instead.');
25
26
27 function ReadStream(fd, options) {
28   if (!(this instanceof ReadStream))
29     return new ReadStream(fd, options);
30
31   options = util._extend({
32     highWaterMark: 0,
33     readable: true,
34     writable: false,
35     handle: new TTY(fd, true)
36   }, options);
37
38   net.Socket.call(this, options);
39
40   this.isRaw = false;
41   this.isTTY = true;
42 }
43 inherits(ReadStream, net.Socket);
44
45 exports.ReadStream = ReadStream;
46
47 ReadStream.prototype.setRawMode = function(flag) {
48   flag = !!flag;
49   this._handle.setRawMode(flag);
50   this.isRaw = flag;
51 };
52
53
54 function WriteStream(fd) {
55   if (!(this instanceof WriteStream)) return new WriteStream(fd);
56   net.Socket.call(this, {
57     handle: new TTY(fd, false),
58     readable: false,
59     writable: true
60   });
61
62   var winSize = [];
63   var err = this._handle.getWindowSize(winSize);
64   if (!err) {
65     this.columns = winSize[0];
66     this.rows = winSize[1];
67   }
68 }
69 inherits(WriteStream, net.Socket);
70 exports.WriteStream = WriteStream;
71
72
73 WriteStream.prototype.isTTY = true;
74
75
76 WriteStream.prototype._refreshSize = function() {
77   var oldCols = this.columns;
78   var oldRows = this.rows;
79   var winSize = [];
80   var err = this._handle.getWindowSize(winSize);
81   if (err) {
82     this.emit('error', errnoException(err, 'getWindowSize'));
83     return;
84   }
85   var newCols = winSize[0];
86   var newRows = winSize[1];
87   if (oldCols !== newCols || oldRows !== newRows) {
88     this.columns = newCols;
89     this.rows = newRows;
90     this.emit('resize');
91   }
92 };
93
94
95 // backwards-compat
96 WriteStream.prototype.cursorTo = function(x, y) {
97   require('readline').cursorTo(this, x, y);
98 };
99 WriteStream.prototype.moveCursor = function(dx, dy) {
100   require('readline').moveCursor(this, dx, dy);
101 };
102 WriteStream.prototype.clearLine = function(dir) {
103   require('readline').clearLine(this, dir);
104 };
105 WriteStream.prototype.clearScreenDown = function() {
106   require('readline').clearScreenDown(this);
107 };
108 WriteStream.prototype.getWindowSize = function() {
109   return [this.columns, this.rows];
110 };