how to read terminal input in node.js? - javascript

I want to do some local node test before push the code to server.
how can I read terminal input as a input for my js script?
readline or something

I think there is no need to use third party library, if you just want to get command line params.
You can use process.argv property of process node core object.
just use process.argv & you are good to go.It returns an array in which by default there is 2 element, at 0 index Node execution directory & at 1 index working directory, so cmd line params start from 2nd index.
So in nutshell, you can access cmd line params using process.argv[2] onwards.

For commandline app you can use nicl. you can make call to your chat module or websocket or whatever based on your logic.
var nicl = require("nicl");
function main() {
nicl.printLine("Hello, what is your name?");
var name = nicl.readLine();
//call to websocket or any chat module
nicl.printLine("Great to meet you, " + name + "!");
process.exit(0);
}
nicl.run(main);

Related

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.

Commander.js display help when called with no commands

I'm using commander.js to write a simple node.js program that interacts with an API. All calls require the use of subcommands. For example:
apicommand get
Is called as follows:
program
.version('1.0.0')
.command('get [accountId]')
.description('retrieves account info for the specified account')
.option('-v, --verbose', 'display extended logging information')
.action(getAccount);
What I want to do now is display a default message when apicommand is called without any subcommands. Just like when you call git without a subcommand:
MacBook-Air:Desktop username$ git
usage: git [--version] [--help] [-C <path>] [-c name=value]
[--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
[-p | --paginate | --no-pager] [--no-replace-objects] [--bare]
[--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
<command> [<args>]
These are common Git commands used in various situations:
start a working area (see also: git help tutorial)
clone Clone a repository into a new directory
init Create an empty Git repository or reinitialize an existing one
...
You can do something like this by checking what arguments were received and if nothing other than node and <app>.js then display the help text.
program
.version('1.0.0')
.command('get [accountId]')
.description('retrieves account info for the specified account')
.option('-v, --verbose', 'display extended logging information')
.action(getAccount)
.parse(process.argv)
if (process.argv.length < 3) {
program.help()
}
When you're trying to pass a command, it stores the commands in process.argv array.
You can add a conditon like at the end of your code like -:
if(process.argv.length <= 2)
console.log(program.help());
else
program.parse();
What I want to do now is display a default message when apicommand is called without any subcommands. Just like when you call git without a subcommand
The help is automatically displayed from Commander 5 onwards if you call without a subcommand.
(Disclosure: I am a maintainer of Commander.)

redis.exceptions.ResponseError: MOVED error in redis set operation

I have created a Redis cluster with 30 instances (15 masters/ 15 nodes). With python code i connected to these instances, i found the masters and then i wanted to add some keys to them.
def settomasters(port, host):
r = redis.Redis( host=host, port=port )
r.set("key"+port,"value")
Error:
redis.exceptions.ResponseError: MOVED 12539 127.0.0.1:30012
If i try to set key from redis-cli -c -p portofmyinstance sometimes i get a redirection message that tells where the keys stored.
I know that in case of get requests for example, a smart client is needed in order to redirect the requests to the correct node (the node that holds the key) otherwise a moved error occurs. Is it the same situation? I need to catch the redis.exceptions.ResponseError and try to set again?
while True:
try:
r.set("key","value")
break
except:
print "error"
pass
My first try was above code but without solution. The set operation never succeeds.
On the other hand below code in javascript does not throw an error and i cannot figure the reason:
var redis = require('redis-stream'),
client = new redis(30001, '127.0.0.1');
// Open stream
var stream = client.stream();
// Example of setting 200 records
for(var record = 0; record <200; record++) {
var command = ['set', 'qwerty' + record, 'QWERTYUIOP'];
stream.redis.write( redis.parse(command) );
}
stream.on('close', function () {
console.log('Completed!');
});
// Close the stream after batch insert
stream.end();
Any help will be appreciated, thanks.
with a redis cluster you can use the normal redis client only if you "find for the certain key the slot that belongs and then the slots that each master serves. With this information i can set keys to the correct node without moved redirection errors." as #Antonis said. Otherwise you need http://redis-py-cluster.readthedocs.io/en/master/

Run javascript file from MongoDB C# driver

I'm trying to use Variety, a custom tool/script for MongoDB (2.6) in the C# driver for MongoDB.
I was able to run it successfully through the commandline, but I'm unsure how to run it's equivalent in the C# driver.
bin\mongo db --eval "var collection = 'coll', limit = 20" bin\variety.js
1. Javascript location
I ran the command above when the javascript was located in bin\ next to mongo.exe. Following the manual I went on and placed the file in \data\db\scripts. However I also read about the system.js file.
Is placing it in \data\db\scripts the right way? Or do I have to register it in system.js?
2. Running the script
This example on running a stored procedure in MongoDB shows how to execute a method with two arguments. However the Variety tool uses some sort of context variables which I need to provide in order for it to execute (collection and limit for instance). In the commandline they are provided as string which is evaluated before the name of the script file.
What is the equivalent of the commandline execution? I can't get the result2 variable right. How do I pass an entire script file instead of a function name?
MongoClient client = new MongoClient("mongodb://0.0.0.0/db");
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("db");
BsonValue result1 = db.Eval("var collection = 'coll', limit = 20");
BsonValue result2 = db.Eval(result1.AsBsonJavaScript.Code, "variety.js");

OpenTok NodeJS Video Chat

I've been following along with this
https://github.com/songz/OpenTokNodeJS
I posted an issue but thought I would try here as well.
I've been working at this for a minute and can't seem to get it running.
Here's my error
TypeError: Object Error: Invalid Key or Secret has no method 'createSession'
at port (/Users/rswain/Desktop/Art/videotok/app.js:42:19)
at callbacks (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:164:37)
at param (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:138:11)
at param (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:135:11)
at pass (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:145:5)
at Router._dispatch (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:173:5)
at Object.router (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:33:10)
at next (/Users/rswain/Desktop/Art/videotok/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at resume (/Users/rswain/Desktop/Art/videotok/node_modules/express/node_modules/connect/lib/middleware/static.js:65:7)
at SendStream.error (/Users/rswain/Desktop/Art/videotok/node_modules/express/node_modules/connect/lib/middleware/static.js:80:37)
TypeError: Object Error: Invalid Key or Secret has no method 'createSession'
at port (/Users/rswain/Desktop/Art/videotok/app.js:42:19)
at callbacks (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:164:37)
at param (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:138:11)
at param (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:135:11)
at pass (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:145:5)
at Router._dispatch (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:173:5)
at Object.router (/Users/rswain/Desktop/Art/videotok/node_modules/express/lib/router/index.js:33:10)
at next (/Users/rswain/Desktop/Art/videotok/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at resume (/Users/rswain/Desktop/Art/videotok/node_modules/express/node_modules/connect/lib/middleware/static.js:65:7)
at SendStream.error (/Users/rswain/Desktop/Art/videotok/node_modules/express/node_modules/connect/lib/middleware/static.js:80:37)
I'm guessing it has something to do with my api key, and to be honest i'm not 100% where i'm supposed to even put it. I've tried a few methods. First I replaced the lines in app.js
var OTKEY = process.env.TB_KEY;
var OTSECRET = process.env.TB_SECRET;
with
var OTKEY = (my api key);
var OTSECRET = (my secret);
but when i run $ node app.js, nothing happens, and I get the error
I've also tried adding the key and secret to the package.json file like so
{
"name":"NodeOpenTok",
"version":"0.0.2",
"dependencies":{
"opentok":"44456952",
"express":"7f2ecae114cd4095a1ed689ff63910f1ea79444b",
"ejs":""
}
}
but I get the same errors. any ideas?
thanks for making this, looks great, can't wait to get it working!
my name is Song and I believe I can help you. When I wrote the following code, I am simply setting the variables OTKEY and OT_SECRET.
var OTKEY = process.env.TB_KEY;
var OTSECRET = process.env.TB_SECRET;
You can similarly replace the key and secret directly:
var OTKEY = "1234";
var OTSECRET = "1abbababaabcabc";
process.env.TB_KEY and process.env.TB_SECRET pulls out the variables from my system environment . I do it this way because of security reasons ( I don't want to accidentally push my key/secret to github ). To set variables for your system environment, open your bash profile and add the following lines:
export TB_KEY='1234'
export TB_SECRET='1abbababaabcabc'
Again, setting the environment variables is not necessary to get your code to work. The simplest way to go is to simply set the variables OTKEY and OTSECRET.
Good Luck!

Categories