Javascript equivalent of bash read -p - javascript

In order to get familiar with javascript and eventually explore the possible to restify the js script, i'm trying to convert a bash script into a javascript (with the intent on running the js the same way i'd run the bash script). So far i've been able to replicate most of bash functionnality in js except for parameter prompts.
For example, in bash I prompt the script user for parameter this way:
read -p "Are you a god? (Y/N) " ANSWER
with the effect that whatever input the user enter will be stored in variable ANSWER
from the i can continue with my script with something like this:
if [ "$ANSWER" = "Y" ]; then echo "You lying puny human"; else echo "Then die!"; fi
Now, i've looked at various options that javascript offer like the readline module or the prompt module but unless i'm missing something from the examples provided in the documentation
https://nodejs.org/api/readline.html#readline_readline for readline and
https://github.com/flatiron/prompt for prompt
It looks like it would do what i'm looking for but when i try that in an actual script, i can't seem to get my variable outside of the scope of the prompt/readline function
for example if i try this:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('What do you think of Node.js? ', (answer) => {
// TODO: Log the answer in a database
console.log('Thank you for your valuable feedback:', answer);
rl.close();
});
echo(answer);
i'll get an error saying that the answer variable used in the echo is not declared
if i try this instead:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var result
rl.question('What do you think of Node.js? ', (answer) => {
result = answer
console.log('Thank you for your valuable feedback:', answer);
rl.close();
});
echo(result);
the echo will be resolved when the prompt occurs and i'll see an undefined being echoed on my prompt line and then i'll be able to provide a value to the prompt and then once the prompt is resolved the script will end
My examples are using readline module but i pretty much got the same results with prompt
so to resummarize my question after this lenghty context:
can i get somewhat the same behavior in javascript that i get in bash using read -p in the sense that i have some script being run, then it pause to prompt the user then it carry on with the rest of the script?

Related

Node.js : How to make spawn function synchronous instead of using spawnSync?

I'm currently using spawnSync and stdio:inherit to get the logs printed on my console. However I'm looking for custom logging to a separate file, in case if anything fails during the spawn.
I'm looking to create a wrapper around
spawn
so that it has following properties :
Synchronous function where output is stored in a variable
View output on the console
Write stdout and stderr to a file
For instance :
const result = spawnSync('ls', [ '-l', '-a' ], { stdio: 'inherit'}); // will print as it's processing
console.log(result.stdout); // will print null
const result = spawnSync('ls', [ '-l', '-a' ], { encoding: 'utf-8' }); // won't print anything
console.log(result.stdout); // will print ls results only on completion
I need result such that it will print while it's processing and write to a file at the same time
Also I'm looking for some strategy or solution from node.js side apart from shell scripting
I guess we can't make all three possible because of the limitation of node.js
As per the documentation
If we are trying to use stdio:'inherit' , we can either redirect output to parent stdout stream or file using
fs.openSync()
Because of the limitation, we can't use custom streams too.

Node.js - Serverside Command Promp Commands input?

I´m writing a Web MMO with Node.js and for debug and maintenance reasons i would love to have the ability to open my SSH connection, where i also start my server, and write a command like "logout all".
So what are my options to get command prompt input and use it while my server runs?
Example:
I start my server with "node app.js" - server starts.
Now i want to write something into the command prompt - how do i get said input so i can use it in my code?
I was trying to read into node.js-readline but i cant seem to find much about it and everything that i found about it needs a "question" to be asked so it can get the input.
I would love to have something like this:
var command = getCommandlineInput(); //command = "logout all"
It need to get any input any time. A callback function would be good aswell, so i can direktly run it throu a checkCommand() function.
So i just figured out how to do this:
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
readline.on('line', (input) => {
useCommand(input);
});
function useCommand (input)
{
switch (input) {
case "show userlist":
CMD_showUserlist();
break;
}
}
First we initiate readline.
With readline.on we listen for any input you type into the command prompt.
useCommand() takes this input and chose what function to run.
How to work with the given input string is up to you, in my example i just made a hard coded command "show userlist".

How to write the argument of a function in the terminal with node js

I'm using this code to connect to mailchimp API, get a list of members and put all their email adresses in an array:
var mailchimpMarketing = require("#mailchimp/mailchimp_marketing");
mailchimpMarketing.setConfig({
apiKey: "MY API KEY",
server: "MY SERVER",
});
async function getArrayEmailMembersFromMailchimpListID(listID){
const response = await mailchimpMarketing.lists.getListMembersInfo(listID);
const emailsMailchimp = response.members.map(member => member.email_address);
console.log(emailsMailchimp)
return emailsMailchimp;
}
getArrayEmailMembersFromMailchimpListID("MY LIST ID")
My problem is that I want to write the list ID "MY LIST ID" in my terminal and not in my code when I'm starting the script. Something like that:
$node test.js MyListID
Instead of
$node test.js
But I don't know how to do it.
I think it's possible with process.argv or minimist but I don't understand how they work. Can someone explain it to me or is their any other possibility ?
From the Node-JS v8.x documentation:
The process.argv property returns an array containing the command line
arguments passed when the Node.js process was launched. The first
element will be process.execPath. See process.argv0 if access to the
original value of argv[0] is needed. The second element will be the
path to the JavaScript file being executed. The remaining elements
will be any additional command line arguments.
So in your case you can simply do:
getArrayEmailMembersFromMailchimpListID(process.argv[2])
Of course you should add some error-handling for this to make it more robust.

Hide console's user input after return/new line

What I'd like to do is hiding/erasing all users input from a nodejs console app once entered, so that when the user inserts some text and then types enter, he won't be able to read what he just entered in the console anymore (so basically remove the line right after it's been entered).
This should be pretty simple to achieve but I have no idea how to do it =).
Thank you in advance
EDIT:
Let's say we have this code:
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
rl.question('How ya doin?\n', input => {
console.log('seems like you\'r doing ' + input.toString())
})
The app prompts a question
The user answers "Fine" (This line shouldn't be there anymore after the user presses enter)
The program says "seems like .... Fine"
Looks like readline can already handle this for you..
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
rl.question('How ya doin?\n', input => {
readline.moveCursor(process.stdout, 0,-1)
console.log('seems like you\'r doing ' + input.toString())
})
According to Bash HOWTO
Move the cursor up N lines:
\033[<N>A
To overwrite user's 1 line input with your output you should move 1 line up and print your output. It will look like this:
console.log('\033[1A' + 'seems like you\'r doing ' + input.toString());
UPDATE:
Found a nice answer :)
How do you edit existing text (and move the cursor around) in the terminal?

Input through node JS in Terminal

I am trying to make a program in Node.JS that will display some text, using console.log("");, then wait for the user to input some commands. First of all, I want to run this through the Linux Terminal on Cloud9 IDE, which does not pause long enough to input anything. Second of all, I want it to be like its own little command line. (I mean respond to certain case-sensitive commands, and ignore anything else.) Can anyone help with this?
Check out prompt. https://www.npmjs.com/package/prompt It works like:
var prompt = require('prompt');
prompt.start();
prompt.get(['hello'], function (err, result) {
console.log('you typed ' + result.hello);
});
Will do:
$ nodejs prompt.js
prompt: hello: world
you typed world
Happy coding ^^

Categories