Home > Back-end >  How to get process.argv inputs and write them to a file using fs.writeFileSync
How to get process.argv inputs and write them to a file using fs.writeFileSync

Time:05-24

I'm learning node.js and I want to get the inputs from the user and write them to a file called points.txt

const process = require("process")
const fs = require("fs")
const [, , num1,num2,num3,num4] = process.argv
fs.writeFileSync('points.txt', process.argv[2,3,4,5])
node app.js 1 2 3 4

However, with this code, I only see 4 If I were to then go into the points.txt. I should see 1 2 3 4

CodePudding user response:

The expression process.argv[2,3,4,5] redounds to process.argv[5] (those comma operators just evaluate each int and the whole expression's value ends up as the value of the last int).

Since the code has assigned the params it wants to write as the num variables, write those...

const process = require("process")
const fs = require("fs")
const [, , num1,num2,num3,num4] = process.argv
console.log(num1, num2, num3, num4)
fs.writeFileSync('points.txt', [num1,num2,num3,num4])

CodePudding user response:

You can't use the , operator for getting several values that way. The comma operator returns it's last operand, so your code is equal to process.argv[5] which should return 4 in this case. You can use the slice method instead:

process.argv.slice(2);

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

For converting the returned array of the slice call into a string, you can use the join method: process.argv.slice(2).join(' ')

  • Related