-1

Just started learning Node and I'm reviewing exercises from class today. Can't remember what the "process.argv[2]" refers to when writing a new file using fs. I'm thinking [0] would refer to "node", and [1] would refer to the name of the file that you're creating ("log.txt"), so what's this code referring to at [2]? This code works fine and outputs "Success!", btw, just trying to understand it a bit better. Thanks!

var fs = require("fs");

fs.writeFile("log.txt", process.argv[2], function(err) {
  if (err) {
    return console.log(err);
  }

  console.log("Success!");
});
rgrzdv
  • 1
  • 1

2 Answers2

0

Those are the arguments you supply when you launch your app with node. It starts in 2 because the first two parameters are the command and the file.

process.argv = ['node', 'yourscript.js', ...]

Manuel Guzman
  • 483
  • 5
  • 15
0

This is a holdover from the early days of UNIX and the C language, a very useful holdover.

If you run your nodejs program by saying this to your command line

node whatever whatelse

Then process.argv[2] contains the value whatelse. The words on the command line end up in that argv array numbered from zero.

In your example, it looks like you will use

node myprogram.js whatever

to write the word "whatever" to the file called log.txt. Why? the code you showed mentions process.argv[2] in the second parameter to fs.writeFile(). That parameter supplies the information you want written to the file.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
  • Thank you for the example. So when writing a new file as in my code, what value does "process.argv[2]" contain? If I understand, [0] is "node", and [1] is "index.js" (the name of the file the "fs.writeFile" code is in), but I'm not understanding what the exact value of [2] would be. To get this code to run and actually write the "log.txt" file, I just need to enter "node index.js" (which are positions [0] and [1]). So is the value of [2] "fs"? or "fs.writeFile"? or "log.txt"? – rgrzdv Oct 13 '20 at 00:50