Node.js readline module: stop reprinting the line just read - node.js

I'm using the readline module in Node (12) to accept user input as such:
import * as readline from "readline";
process.stdin.setEncoding('utf-8');
console.log("input is a TTY?",process.stdin.isTTY);
const rl = readline.createInterface({input: process.stdin, output: process.stdout, prompt: '> '});
rl.prompt();
rl.on('line' ,inputLine => { inputStringLines.push(inputLine); rl.prompt(); });
rl.on('close',() => { console.log('input has closed'); main(); });
The lines are correctly captured into my inputStringLines array but annoyingly, the process is printing out every line just read:
How can I get rid of the extra lines (the ones without the > prompt)

I fixed it by changing how run my script. Before, I used nodemon with node's -r ts-node/register option. The issue went away when I switched to using ts-node-dev to execute the script.
Note also that process.stdin.isTTY is now correctly set whereas it was undefined before (look at the first line in the image below, vs in the original post)
Still don't know the root cause, but I'm happy to move on.

Related

How to get variable from input NodeJs

I want to get a value from input
const readline = require('node:readline/promises').createInterface({
input: process.stdin,
output: process.stdout
})
const value = await readline.question('enter :');
console.log(value)
readline.close()
And then I get an Error "SyntaxError: await is only valid in async functions and the top level bodies of modules"
On the other hand in the docs example:
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'process';
const rl = readline.createInterface({ input, output });
const answer = await rl.question(
'What do you think of Node.js? '
);
console.log(
`Thank you for your valuable feedback: ${answer}`
);
rl.close();
I copy this example and get the same error. I cant use readline synchronously. I want input a value, some variable will equals this value, and THEN it will console.log(). I dont want to use "Prompt" module. TY
Your issue is because you are trying to use top-level-await.
Now this is possible in modern nodejs (16+ I think), but you need to tell explicitly node to use modules, like your in your second code.
Try to upgrade nodeJS to the latest version 18, it should run fine.
(Also you may need to hint node on using modules explicitly, for that either name your file using the extension .mjs or specify "type": "module" in your package.json
Working example using .mjs and current node v18.6 the code is copy pasted from your question, no changes made.

Nodejs Is there a way to kill a process then start it again

So I'm working on a little project and I want something that lets me restart a process Since I start it by requiring the file so like
switch (start) {
case "-dev":
require("./path/to/file")
break;
}
and I want to have a function that when you type rs in the console it will restart it without the user needing to run node . -dev again. So Something like nodemon but not...
I have this but I don't know how to fully do something like it
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
let cmd = function () {
rl.question('', function (answer) {
switch (answer) {
case "rs":
process.exit()
require("./path/to/file")
}
cmd();
});
};
cmd();
but that wouldn't work.. That's why I'm confused
Note: I do not want to use Nodemon
There is a module named child_process on NPM. A function available is spawn. The spawn command is able to run programs and get output from them. The second there is output, it closes. Note that it opens in a new window. Here is my proposed code to restart your application
var cmd = childprocess.spawn("cmd", [ "/k", "start", "cmd", "/k", "node", ".", "-dev"]);
cmd.stdout.on("data", () => {
process.exit()
})
This feels like a clunky solution, but it does work.
More information on the child_process module

Is it possible to push text to prompt input?

I am using the prompt module, node version 12.4.0
I am wondering if its possible to push a string to the 'input field' of a prompt.get()
The following script displays a (double) "prompt: "
After 5 seconds, it inserts the text "This is a test"
When an enter command is given, the string is not recognized as input.
It isn't possible to edit the string before pressing enter either.
(type anything before 5 sec and press enter, and the input WILL display)
End-goal: to have commands send to prompt from external source, but give the end user the ability to modify the commands before entering.
I tried process.stdout.write, process.stdin.write
I also tried to replace process.std*.write with prompt.std*.write
The answer might be os-specific, but I have tried this code both under Win10 x64 as well as Linux
const prompt = require("prompt");
function myFunc() {
process.stdin.write("This is a test");
}
setTimeout(myFunc, 5000);
prompt.get({
properties: {
test: {
description: "prompt"
}
}
}, (err, result)=> {
console.log("input: "+ result.test);
});
actual result:
~/Nodejs/temp$ node index.js
prompt: prompt: This is a test
input:
~/Nodejs/temp$
desired result:
~/Nodejs/temp$ node index.js
prompt: prompt: This is a test
input: This is a test
~/Nodejs/temp$
After digging into how the prompt module works, I 'solved' this myself.
prompt uses readline behind the curtains, and readline has a .write function that does what I need, send editable text to the prompt.
prompt itself does not extend this function, and since it hasnt been maintained for 3 years, I switched to readline instead.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: 'prompt> '
});
rl.prompt();
rl.on('line', (line) => {
console.log(line);
rl.prompt();
}).on('close', () => {
console.log('Have a great day!');
process.exit(0);
});
// simulate external input, and write to prompt>
function myFunc() {
rl.write("This is a test");
}
setTimeout(myFunc, 5000);

Prompt module in NodeJS repeating the input

I'm making an application using NodeJS and its a CLI application; to get the input from the user, I'm using the "prompt" module. I can use it, but while typing in the prompt's prompt, each character is getting repeated, however the output is fine! The code is below. Please Help.
prompt.start();
prompt.get({
properties: {
name: {
description: "What is your name?".magenta
}
}
}, function (err, result) {
console.log("You said your name is: ".cyan + result.name.cyan);
});
IMAGE:
Before using the "prompt" module, I used the ReadLine interface; sadly I had the same problem. However, the fix was simple:
Remove the rli.close(); and then run it.
Then re-add the rli.close(); and it works!
Thanks mscdex for the input, though :)
FWIW if you just need simple prompting, you can use the built-in readline module's question() method (which does not exhibit the double output issue). Example:
var readline = require('readline');
var rli = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rli.question('What is your name? ', function(answer) {
console.log('You said your name is: ' + answer);
rli.close();
});

How do I open a terminal application from node.js?

I would like to be able to open Vim from node.js program running in the terminal, create some content, save and exit Vim, and then grab the contents of the file.
I'm trying to do something like this:
filename = '/tmp/tmpfile-' + process.pid
editor = process.env['EDITOR'] ? 'vi'
spawn editor, [filename], (err, stdout, stderr) ->
text = fs.readFileSync filename
console.log text
However, when this runs, it just hangs the terminal.
I've also tried it with exec and got the same result.
Update:
This is complicated by the fact that this process is launched from a command typed at a prompt with readline running. I completely extracted the relevant parts of my latest version out to a file. Here is it in its entirety:
{spawn} = require 'child_process'
fs = require 'fs'
tty = require 'tty'
rl = require 'readline'
cli = rl.createInterface process.stdin, process.stdout, null
cli.prompt()
filename = '/tmp/tmpfile-' + process.pid
proc = spawn 'vim', [filename]
#cli.pause()
process.stdin.resume()
indata = (c) ->
proc.stdin.write c
process.stdin.on 'data', indata
proc.stdout.on 'data', (c) ->
process.stdout.write c
proc.on 'exit', () ->
tty.setRawMode false
process.stdin.removeListener 'data', indata
# Grab content from the temporary file and display it
text = fs.readFile filename, (err, data) ->
throw err if err?
console.log data.toString()
# Try to resume readline prompt
cli.prompt()
The way it works as show above, is that it shows a prompt for a couple of seconds, and then launches in to Vim, but the TTY is messed up. I can edit, and save the file, and the contents are printed correctly. There is a bunch of junk printed to terminal on exit as well, and Readline functionality is broken afterward (no Up/Down arrow, no Tab completion).
If I uncomment the cli.pause() line, then the TTY is OK in Vim, but I'm stuck in insert mode, and the Esc key doesn't work. If I hit Ctrl-C it quits the child and parent process.
You can inherit stdio from the main process.
const child_process = require('child_process')
var editor = process.env.EDITOR || 'vi';
var child = child_process.spawn(editor, ['/tmp/somefile.txt'], {
stdio: 'inherit'
});
child.on('exit', function (e, code) {
console.log("finished");
});
More options here: http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options
Update: My answer applied at the time it was created, but for modern versions of Node, look at this other answer.
First off, your usage of spawn isn't correct. Here are the docs. http://nodejs.org/docs/latest/api/child_processes.html#child_process.spawn
Your sample code makes it seem like you expect vim to automatically pop up and take over the terminal, but it won't. The important thing to remember is that even though you may spawn a process, it is up to you to make sure that the data from the process makes it through to your terminal for display.
In this case, you need to take data from stdin and send it to vim, and you need to take data output by vim and set it to your terminal, otherwise you won't see anything. You also need to set the tty into raw mode, otherwise node will intercept some of the key sequences, so vim will not behave properly.
Next, don't do readFileSync. If you come upon a case where you think you need to use a sync method, then chances are, you are doing something wrong.
Here's a quick example I put together. I can't vouch for it working in every single case, but it should cover most cases.
var tty = require('tty');
var child_process = require('child_process');
var fs = require('fs');
function spawnVim(file, cb) {
var vim = child_process.spawn( 'vim', [file])
function indata(c) {
vim.stdin.write(c);
}
function outdata(c) {
process.stdout.write(c);
}
process.stdin.resume();
process.stdin.on('data', indata);
vim.stdout.on('data', outdata);
tty.setRawMode(true);
vim.on('exit', function(code) {
tty.setRawMode(false);
process.stdin.pause();
process.stdin.removeListener('data', indata);
vim.stdout.removeListener('data', outdata);
cb(code);
});
}
var filename = '/tmp/somefile.txt';
spawnVim(filename, function(code) {
if (code == 0) {
fs.readFile(filename, function(err, data) {
if (!err) {
console.log(data.toString());
}
});
}
});
Update
I seeee. I don't think readline is as compatible with all of this as you would like unfortunately. The issue is that when you createInterface, node kind of assumes that it will have full control over that stream from that point forward. When we redirect that data to vim, readline is still there processing keypresses, but vim is also doing the same thing.
The only way around this that I see is to manually disable everything from the cli interface before you start vim.
Just before you spawn the process, we need to close the interface, and unfortunately manually remove the keypress listener because, at least at the moment, node does not remove it automatically.
process.stdin.removeAllListeners 'keypress'
cli.close()
tty.setRawMode true
Then in the process 'exit' callback, you will need to call createInterface again.
I tried to do something like this using Node's repl library - https://nodejs.org/api/repl.html - but nothing worked. I tried launching vscode and TextEdit, but on the Mac there didn't seem to be a way to wait for those programs to close. Using execSync with vim, nano, and micro all acted strangely or hung the terminal.
Finally I switched to using the readline library using the example given here https://nodejs.org/api/readline.html#readline_example_tiny_cli - and it worked using micro, e.g.
import { execSync } from 'child_process'
...
case 'edit':
const cmd = `micro foo.txt`
const result = execSync(cmd).toString()
console.log({ result })
break
It switches to micro in a Scratch buffer - hit ctrl-q when done, and it returns the buffer contents in result.

Resources