Take input from node call nodejs - node.js

Just wondering, how do you take input directly from the node call? I know you can do it in Python. Here is an example of what I want to achive:
Code:
function main(x,y) {
return x * y;
}
Command Call:
node index.js 2 2
Or something.

you can use process.argv
let inputArr=process.argv.slice(2);
console.log(inputArr) // [2,2]
we are skipping the first two element of the array process.argv because the first two elements will be always - node and the path to your script

You can use process.argv this will return an array containing the arguments you passed in CLI
Ref: https://nodejs.org/en/knowledge/command-line/how-to-parse-command-line-arguments/

Related

How to convert a hash ref in one line to a constant in perl

I'm using Sphinx::Search.
Is there is a easier way for this code example to convert a string to a constant?
use Sphinx::Search;
my $config = {
x => 'SPH_MATCH_EXTENDED2',
};
my $x = $config->{x};
print Sphinx::Search->$x(); # output: 6
I have used advice from
How do I access a constant in Perl whose name is contained in a variable?
and this example works, but if I am always using a string from a hash then do I need to put it into a separate variable to use it in this way?
my $x = $config->{x};
print Sphinx::Search->$x(); # output: 6
Is there a one- liner for this?
# does not work
print Sphinx::Search->$config->{x}();
You can create a reference to the value and immediately dereference it:
Sphinx::Search->${ \$config->{x} };
(If there are no arguments, the () is optional).
I'm guessing that SPH_MATCH_EXTENDED2 is the name of a constant that is exported by Sphinx::Search. The problem is that these are implemented as a subroutine with no parameters, so you may use them only where a bare subroutine name will be understood by Perl as a call, or where an explicit call is valid ( SPH_MATCH_EXTENDED2() )
The easiest solution is to avoid quoting the hash value at all, like so
my $config = { x => SPH_MATCH_EXTENDED2 }
and afterwards, you may use just
$config->{x}; # 6
instead of calling a pseudo class method

Is there is option to evaluate values in nodejs without using eval or safe-eval?

I am trying to create a function in javascript having the same behavior as eval as it is not that much secure as safe-eval npm package. When I am trying to use safe-eval library rather than eval it doesn't support many of the functions as if, switch etc so it is giving me error as
SyntaxError: Unexpected token if
So I tried to write a code for same but facing some issues in that as well.
Is Anyone know how to use the safe-eval for condition execution or is anyone knows how to write a similar customized function/method for achieving the same goal.
thanks !!
The safe-eval npm page says of the input:
the JavaScript code must be an expression (something which evaluates to a value).
if(...) { ... } is a statement, not an expression.
The simple solution here is one that is already suggested by the documentation on that same NPM page: wrap your statements inside of a function expression that you immediately call.
var code = '(function square(b) { return b * b; })(5)'
var evaluated = safeEval(code)
You could put anything inside of that function, including statements:
var code = '(function square(b) { if(b === 5) { return "yes"; } else { return 0; } })(5)'
var evaluated = safeEval(code)
See the documentation: (emphasis added)
Currently, it works only with Node.js, and the JavaScript code must be an expression (something which evaluates to a value).
if is a statement, not an expression.
You can make it evaluate statements by wrapping them in an IIFE, which is an expression.

node.js \ get params from around the chain, and keep it linear [duplicate]

This question already has answers here:
How do I access previous promise results in a .then() chain?
(17 answers)
Closed 6 years ago.
can I keep the code clean like that and fetch -paramFromA & paramFromB?
all of the functions here return new Promise
var a = helper.getAccountPromise(tokens);
var b = a.then(helper.getFundingPromise)
var c = b.then(helper.createCampignPromise(paramFromA, paramFromB))
UPDATE:
let's say I'll do
var a = helper.getAccountPromise(tokens);
var b = a.then(helper.getFundingPromise)
var c = helper.createCampignPromise(a, b))
....
createCapmaignPromise(a,b){
// do I wait for a here? a.then ?
// how do I extract the response here - console.log(a.response) ?
// same for b
}
.then() is always called with one argument, which is the value the promise was resolved with.
I assume paramFromA and paramFromB mean the return values from Promises "a" and "b", so in your chain "c"'s then will only have access to paramFromB.
You could
var c = Promise.all(a, b).then(/* two item array is passed as single argument here */)
In promise libraries like bluebird, you have a .spread() method instead of .then() that spreads the array returned from Promise.all() into two arguments, but you can also use the ES6 ... spread operator.
If you need the promises to run in sequence and pass the return value from a to c, you either have to pass it along from b or store it in a variable outside of the closure in .then();

Node.js Q ninvoke multiple arguments

How would one pass multiple arguments into Q ninvoke?
For example:
exports.getBalance = function () {
return Q.ninvoke(library, 'method', **[Arguments]**);
}
At the moment I have
return Q.ninvoke(library, 'method', '*', 6);
Where arguments is an array or list of arguments?
I'd like to reuse my ninvoke call, but sometimes methods take one or more parameters.
Thanks.
Richard.
You can use .nfpost which works like ninvoke only with an arguments array instead of variable arguments:
Q.ninvoke(library, 'method', myArgumentsArray);
You can read more about it here.

Could someone explain what "process.argv" means in node.js please?

I'm currently learning node.js, and I was just curious what that meant, I am learning and could you tell me why this code does what it does:
var result = 0;
for (var i = 2; i < process.argv.length; i++){
result += Number(process.argv[i]);
}
console.log(result);
I know it adds the numbers that you add to the command line, but why does "i" start with 2? I understand the for loop, so you don't have to go into detail about that.
Thank you so much in advance.
Do a quick console.log(process.argv) and you'll immediately spot the problem.
It starts on 2 because process.argv contains the whole command-line invocation:
process.argv = ['node', 'yourscript.js', ...]
Elements 0 and 1 are not "arguments" from the script's point of view, but they are for the shell that invoked the script.
It starts with 2 because the code will be run with
node myprogram.js firstarg secondarg
So
process.argv[0] == "node"
process.argv[1] == "myprogram.js"
process.argv[2] == "firstarg"
Online docs
Your program prints the sum of the numerical values of the "command line arguments" provided to the node script.
For example:
$ /usr/local/bin/node ./sum-process-argv.js 1 2 3
6
From the Node.js API documentation for process.argv:
An array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.
In the above examples those values are:
process.argv[0] == '/usr/local/bin/node'
process.argv[1] == '/Users/maerics/src/js/sum-process-argv.js'
process.argv[2] == '1'
process.argv[3] == '2'
process.argv[4] == '3'
See also the Number(...) function/contructor for JavaScript.
In the node.js, the command line arguments are always stored in an array. In that array, the first element is the node command we refer to because we begin the command line with word “node”. The second element is the javascript (JS) file we refer to that often comes after the node command.
As we know, in the first element in JS array begins from zero, the second element is 1, and it goes 2, 3, 4 and on. Let’s name this array process.argv and add command line arguments x and y. Then, this is how we are going to call these elements:
var process.argv = ['node', 'file.js', ‘x’, ‘y’];
var process.argv [0] = node;
var process.argv [1]= file.js;
var process.argv[2] = x;
var process.argv[3] = y;
In short, element 0 and 1 are native to node.js, and we don't use them when we write any command line argument. That's why we ignore 0 and 1 and always begin from 2.
If we want to loop through the command line arguments, again we have to start from 2. Here is what we use for looping.
for (i = 2; i < process.argv.length; i++){
console.log(process.argv[i]);
}
My answer is not about on how process.argv works -'cause there is a lot of answers here-, instead, it is on how you can get the values using array destructuring syntax.
For example, if you run your script with:
node app.js arthur 35
you can get those values in a more readable way like this:
const [node, script, name, age] = process.argv;
console.log(node); // node
console.log(script); // app.js
console.log(name); // arthur
console.log(age); // 35
You can omit the first and second places of your process.argv, and stay only with name and age:
const [, , name, age] = process.argv;
If you want all the arguments in an array, you can do it using the rest syntax, that collects multiple elements and condenses them into a single element like this:
const [node, script, ...params] = process.argv;
console.log(node); // node
console.log(script); // app.js
console.log(params); // [ 'arthur', '35' ]
and of course, you can omit the first and second places of your process.argv, and stay only with your params:
const [, , ...params] = process.argv;
When you execute it like:
node code.js <argument> <argument>....
It take into account all command line invocation. For process.argv[] array will have ["node","code.js","<argument>",...]
Because of that your arguments that in array start with index 2
process.agrv[i]- basically loops through the command line arguments passed in the terminal while executing the file.
for example- If you run the file as
$ node prog.js 1 2 3 , then process.argv[0]=1 and so on..

Resources