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

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..

Related

Generate variable name with string and value in Lua

Is there a function in Lua to generate a variable name with a string and a value?
For example, I have the first (string) part "vari" and the second (value) part, which can vary. So I want to generate "vari1", "vari2", "vari3" and so on. Something like this:
"vari"..value = 42 should then be vari1 = 42.
Thanks
Yes, but it most likely is a bad idea (and this very much seems to be an XY-problem to me). If you need an enumerated "list" of variables, just use a table:
local var = { 42, 100, 30 }
var[4] = 33 -- add a fourth variable
print(var[1]) -- prints 42
if you really need to set a bunch of variables though (perhaps to adhere to some odd API?), I'd recommend using ("..."):format(...) to ensure that your variables will be formatted as var<int> rather than var1.0, var1e3 or the like.
Th environment in Lua - both the global environment _G and the environment of your script _ENV (in Lua 5.2), which usually is the global environment, are just tables in the end, so you can write to them and read from them the same way you'd write to and read from tables:
for value = 1, 3 do
_ENV[("vari%d"):format(value)] = value^2
end
print(var3) -- prints 3*3 = 9
-- verbose ways of accessing var3:
print(_ENV.var3) -- still 9
print(_ENV["var"]) -- 9 as well
Note that this is most likely just pollution of your script environment (likely global pollution) which is considered a bad practice (and often bad for performance). Please outline your actual problem and consider using the list approach.
Yes. Call:
rawset(table, key, value)
Example:
rawset(_G, 'foo', 'bar')
print(foo)
-- Output: bar
-- Lets loop it and rawget() it too
-- rawset() returns table _G here to rawget()
-- rawset() is executed before rawget() in this case
for i = 1, 10 do
print(rawget(rawset(_G, 'var' .. i, i), 'var' .. i))
end
-- Output: 10 lines - First the number 1 and last the number 10
See: https://lua.org/manual/5.1/manual.html#pdf-rawset
Putting all together and create an own function...
function create_vars(var, start, stop)
for i = start, stop do
print(var .. i, '=>', rawget(rawset(_G, var .. i, i), var .. i))
end
end
And use it...
> create_vars('var', 42, 42)
var42 => 42
> print(var42)
42

Take input from node call nodejs

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/

Understanding string.gsub in Lua

I'm trying to print a gsub string (in Lua) to stdout here how my code look like.
print('string.gsub(\'VEECTORY\',\'EE\',\'I\') =>', string.gsub('VEECTORY','EE','I'))
Everytime I run this, although I get the desired result but I see 1 appearing in the output.
So, the output look like this.
string.gsub('VEECTORY','EE','I') => VICTORY 1
I'm unable to understand what does that 1 stand for but if I used a variable I don't see that 1 anymore.
local replace_string = string.gsub('VEECTORY','EE','I')
print('string.gsub(\'VEECTORY\',\'EE\',\'I\') =>',replace_string)
I get output as
string.gsub('VEECTORY','EE','I') => VICTORY
I also notice that when I run the above code in Lua console
i.e this code
local replace_string = string.gsub('VEECTORY','EE','I')
print('string.gsub(\'VEECTORY\',\'EE\',\'I\') =>',replace_string)
I get the output as nil
What am I missing ?
string.gsub has two return values. The first is result string, while the second is the total number of matches that occurred.
In your example:
string.gsub('VEECTORY','EE','I')
The second return value is 1 because the substitution happened once.
When you assign the result as:
local replace_string = string.gsub('VEECTORY','EE','I')
The first return value is assigned to replace_string, while the second return value is discarded.
You can get the second return value explicitly by:
local replace_string, num = string.gsub('VEECTORY','EE','I')
Finally, in interactive mode, each line is a chunk by itself, so the local variables are out of scope in the next line, therefore you saw replace_string becomes nil. If you use global variables:
replace_string = string.gsub('VEECTORY','EE','I')
print('string.gsub(\'VEECTORY\',\'EE\',\'I\') =>',replace_string)
The output will be as expected in interactive mode as well.

Enumerating Object.keys() in node.js - strange issue

There is an issue with enumerating Object.keys() in node.js that I do not understand. With the following code:
Object.prototype.tuple = function() {
var names = Object.keys(this);
console.log("Dump of names:");
console.log(names);
console.log("FOR loop using indexes:");
for (var k = 0; k < names.length; k++)
{
console.log(names[k]);
}
console.log("FOR loop using enumeration:");
for (var z in names)
{
console.log(z);
}
return this;
};
var x = {a:0, b:0, c:0}.tuple();
I get the following results on the console:
Dump of names:
[ 'a', 'b', 'c' ]
FOR loop using indexes:
a
b
c
FOR loop using enumeration:
0
1
2
tuple
Could somebody explain where does an extra "tuple" come from in the second loop? While defined as function in Object.prototype, it is neither an own property of x object, nor included in names array.
I am using node.js version 0.8.20.
The first loop goes over the properties of x (Object.keys() returns only own properties), while the second one goes over the properties or the array names, including the ones up in the prototype chain.
Thanks to Jonathan Lonowski for clarifications.
I think what #Kuba mentioned above is not correct.
Object.keys, Object.getOwnPropertyNames and other similar method would behave different sightly. Their behaviors are related to a property named enumerable.
I am going to dinner with my friends so I can only give you a helpful link illustrating it. So sorry.
https://developer.mozilla.org/en-US/docs/Enumerability_and_ownership_of_properties

windows node.js REPL command prompt error messages

I am complete new to open source and would really like to use it more. I installed (x86)node.js from nodejs.org. I launched "Node.js command prompt" from the installed list, and executed node.exe. I am trying to to run some sample javascript. Why is it if I do:
>var life = 11;
undefined
^^^^^^^^^
why am I getting this message?
or
>a = [1,2,3]
[1,2,3]
>a.forEach(function (v) {console.log(v);});
1
2
3
undefined
^^^^^^^^^
//still get this, even though the script executed??
>
The console prints the return value of your script, which is undefined
Write this:
"hello";
And press enter. Now the return value should be "hello" and not undefined.
You could also do;
var life = 11; life;
undefined is just the return value of the statements you executed. Only meaningful/useful if you've executed a function, really.

Resources