JavaScript version of while True loop - javascript

I wrote this bit of code
while True:
text = input('type here > ')
print text
I've tried the below but it doesnt seem to be working
I'm having bit of a struggle trying to create a JavaScript version of it, since it seems js while loops constantly rerun but python seems to wait for input before rerunning. I am using the readline module to receive input from the console.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
while (true) {
rl.question('type here > ', text => {
console.log(text)
})
}
Is there something im getting wrong? Im fairly new to programming
Any solutions?

If what you are trying to do is get input from the console in JavaScript you can use NodeJS process.stdin the implementation below :
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let input = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
input += inputStdin;
});
process.stdin.on('end', _ => {
input = input.trim()
.split('\n')
.map(str => str.trim());
// calling the function that works on the input
doSomething();
});
function readInput() {
return input[currentLine++];
}
Sample function to do something with what you get from the console
function doSomething() {
console.log(readInput())
}

Related

Use readline.question after getting a raw key

I'm trying to do the following two things sequentially in a Node.js app:
Get an arbitrary key as user input. (could be a character pressed, or any other key like arrow up/down...)
I'd like to ask the user for an arbitrary text input.
Each step works but if I chain them, the key entered first is always appended to the second input. Additionally the question is written to the console twice.
Here's the full code sample:
// sample.js
const readline = require("readline")
// Read a raw key from stdin as Promise
const getKey = () => new Promise((res) => {
process.stdin.setRawMode(true)
process.stdin.once('keypress', (str, key) => {
process.stdin.setRawMode(false)
res(key)
});
})
// Just promisify the "question" method
const getText = (interface, str) =>
new Promise(res => interface.question(str, res))
const main = async () => {
readline.emitKeypressEvents(process.stdin);
const interface = readline.createInterface({
input: process.stdin,
output: process.stdout
});
console.log("Press a key!")
const key = await getKey()
console.log(`\nYou pressed key "${key.name}"`)
const name = await getText(interface, "What's your name?\n")
console.log(`Your name is "${name}"`)
}
main()
And here's a sample CLI session screencast:
The expected behavior would be that those inputs don't interfere with eachother. Does anyone have a solution for this problem?
My assumtion was that the character from the first input is still unconsumed inside the stdin stream. But attempts to force to consume it were not successfull.

node.js: take input from file using readline and process I/O in windows command prompt

I want to run name.js file from the command prompt using node.js and pass the input file and redirect that output in output.txt,
I am writing a command for this is node name.js < input.txt | > output.txt but this is not working or I am wrong.
name.js look like this:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var _line = "";
rl.on('line', function(line){
_line += line;
});
rl.on('pause', function(_line){
console.log(_line);
});
I have also tried this in Powershell -Command "command"
EDIT:
for example input.txt contain
hello js
hello node
hello world!
now,if i run node name.js < input.txt > output.txt.
i just get return value of console.log()'s "undefined" in output.txt
passing _line to rl.on('pause',function(_line){} hide the global _line that's why it's giving undefined and cmd command is fine.
there is other way to do this by using process I/O of node.js
function YourData(input) {
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
YourData(_input);
});
read more about readline and process I/O

How can we read random number of lines data from nodejs stdin?

I am trying to run a simple program in Visual studio code terminal using node.js which requires reading inputs from the user and the operating on those inputs and printing the results.
I have tried many approaches but have not got success yet. I am using the following code:
process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
process.stdin.on("data", (c) => (input += c));
process.stdin.on("end", () => {
console.log(input);
});
process.stdin.on("SIGINT", () => {
console.log(input);
const { EOL } = require("os");
const lines = input.split(EOL); /*your input text, split by lines*/
console.log(lines);
});
I run the above code in VSCode using the in-built terminal with the command node filename.js. The program runs and keeps taking inputs but it never ends and never triggers "end" block or "SIGINT" block. Finally to stop the program I have to use ctrl+C.
Can someone please help me how to accomplish this as I want to practise solving www.codeforces.com problems on my local machine using VSCode+terminal?
This way it won't quit until you explicitly end the program. You can use process.exit() function to achieve that.
So your program should look like this :
process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
const inputLength = (Math.random()*10 +1) | 0;
console.log(inputLength);
let current=0;
process.stdin.on("data", (c) => {
input += c;
current++;
if(current>= inputLength){
console.clear();
console.log("reached max number of inputs");
console.log(input);
process.exit(0);
}
});
Here is the glitch link. You can test it opening console below and type node server.js
TBH, I don't understand what do you want to achieve, but you can write something like:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
})
rl.on('line', (input) => {
console.log(`Received: ${input}`);
});
when you hit enter, you will see you line. CTRL+C also works
readline is a part of the standard library

Import TXT to be an array

before, i already search the question asked in SOF before i deciding to ask,
like here
or here
but none of it solve my problem..
ok so heres my code :
const file = './PAGE1.txt';
const fs = require('fs');
fs.readFile(file,'utf-8', (e,d)=>{
let textByLine = d.split('\n'); //make it an array
let hasil=textByLine[2];
});
the page1.txt is like
Aa
Ab
Ac
so then i try
console.log(hasil)
it succeeded showing "Ac" on the console.
but when i do
console.log(hasil + " Test")
it shows up "Test"
why its not "Ac Test" ?
thank you for your help.
Edit : this is solved, i just simply add '\r' :
let textByLine = d.split('\r\n'); //make it an array
and now the console show "Ac Test".
now i wanna ask what does this "\r" function?
why i need it to solve my question..
thankyou again :)
const fs = require('fs'); // file system package
const rl = require('readline'); // readline package helps reading data line by line
// create an interface to read the file
const rI = rl.createInterface({
input: fs.createReadStream('/path/to/file') // your path to file
});
rI.on('line', line => {
console.log(line); // your line
});
You can simply use this to log line by line data. But in real world you will use with Promise e.g
const getFileContent = path =>
new Promise((resolve, reject) => {
const lines = [],
input = fs.createReadStream(path);
// handle if cann't create a read strem e.g if file not found
input.on('error', e => {
reject(e);
});
// create a readline interface so that we can read line by line
const rI = rl.createInterface({
input
});
// listen to event line when a line is read
rI.on('line', line => {
lines.push(line);
})
// if file read done
.on('close', () => {
resolve(lines);
})
// if any errors occur while reading line
.on('error', e => {
reject(e);
});
});
and you will use it like this.
getFileContent('YOUR_PATH_TO_FILE')
.then(lines => {
console.log(lines);
})
.catch(e => {
console.log(e);
});
Hope this will help you :)
Edit : this is solved, i just simply add '\r' :
let textByLine = d.split('\r\n'); //make it an array
and now the console show "Ac Test"
now i wanna ask what does this "\r" function?
why i need it to solve my question..
thankyou again :)

How do I implement tab completion in node.js shell?

I was looking for this feature in node.js and I haven't found it.
Can I implement it myself? As far as I know, node.js doesn't load any file at it's startup (like Bash does with .bashrc) and I haven't noticed any way to somehow override shell prompt.
Is there a way to implement it without writing custom shell?
You could monkey-patch the REPL. Note that you must use the callback version of the completer, otherwise it won't work correctly:
var repl = require('repl').start()
var _completer = repl.completer.bind(repl)
repl.completer = function(line, cb) {
// ...
_completer(line, cb)
}
Just as a reference.
readline module has readline.createInterface(options) method that accepts an optional completer function that makes a tab completion.
function completer(line) {
var completions = '.help .error .exit .quit .q'.split(' ')
var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })
// show all completions if none found
return [hits.length ? hits : completions, line]
}
and
function completer(linePartial, callback) {
callback(null, [['123'], linePartial]);
}
link to the api docs: http://nodejs.org/api/readline.html#readline_readline_createinterface_options
You can implement tab functionality using completer function like below.
const readline = require('readline');
/*
* This function returns an array of matched strings that starts with given
* line, if there is not matched string then it return all the options
*/
var autoComplete = function completer(line) {
const completions = 'var const readline console globalObject'.split(' ');
const hits = completions.filter((c) => c.startsWith(line));
// show all completions if none found
return [hits.length ? hits : completions, line];
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
completer: autoComplete
});
rl.setPrompt("Type some character and press Tab key for auto completion....\n");
rl.prompt();
rl.on('line', (data) => {
console.log(`Received: ${data}`);
});
Reference :
https://self-learning-java-tutorial.blogspot.com/2018/10/nodejs-readlinecreateinterfaceoptions_2.html

Categories

Resources