pty.js
pty.js copied to clipboard
Get input data on output listener method
I am using pty.js
in a nodejs application to emulate a interactive terminal. But the I got the input data in the output listener method. Is there a way to get the output data only?
Below is my source code:
var pty = require('pty.js');
var term = pty.spawn('bash', [], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.env.HOME,
env: process.env
});
term.on('data', function(data) {
console.log(data);
});
term.write('echo hello\n');
when running above code, I can see the output:
$ node official.js
echo hello
bash-3.2$ echo hello
hello
bash-3.2$
from the above output you can observe that the input command echo hello
got printed twice in term.on('data' ...)
function. Is there a way to get ride of the input data from the output listener method?
I'm looking for this same solution. Currently, the only thing I could think to do is to capture the input manually in a variable and compare the output with the last known input on each data
event, choosing to ignore the said output if they are equal.
let lastInput = '';
term.on('data', (data) => {
if(lastInput !== data) {
process.stdout.write(data); // instead of console.log to avoid extra newline characters
}
}
process.stdin.on('readable', () => {
const chunk = process.stdin.read();
if (chunk !== null) {
lastInput = chunk;
term.write(chunk);
}
}
The problem with this is that while it seems straight forward, data
and chunk
are of different types. Then once you get past that with everything converted to what it needs to be for comparison, you end up with them having different newline characters. My attempt had lastInput
possessing a trailing \n
and data
possessing \r\n
.
Finally, on top of all of that, stdout doesn't guarantee that the entire string is handed to you on the data
event. I would often get something like this.
t
est
bash-3.2$
My next step is to possibly wait for a newline character before parsing data
. I'm just afraid that there will be scenarios where all of this will cause unintended behavior. It would be much better if the echo could be disabled with a configuration option or something.
Solution
Found this explanation in the node-pty
repo.
process.stdin.setRawMode(true)
I would expect it to work with pty.js
as well.
On that note, this repo hasn't had a commit in a year, so I would consider switching to node-pty
if you're doing anything crucial. I've only recently discovered them, and don't know much about them, but it seems like the community has switched boats.
One might be the continuation of the other. I don't know.
@euroclydon37 node-pty was forked from pty.js about a year ago, here are the main changes:
- Better Windows support
- Better support for recent Node versions
- Converted to TS, added some tests
Checkout the releases for more specifics, 0.4.1 was the first release after forking, 0.6.0 removed pty.js' modification to winpty and updated it to latest.
Loving it so far.