32.3k views
4 votes
I need to get inputs from user which includes personal informations. And this results should be saved and transformed into JSON object and written into another user.json file. For example user inputs "mary,England,22" and this inputs should be written as [{"Name":"mary", "Country": "england", "Age": "22" }] into a JSON file. NODE.JS

1 Answer

5 votes

Final answer:

To get inputs from the user in Node.js and save them as a JSON object in a file, you can use the 'readline' and 'fs' modules. First, prompt the user for input using the 'question' method of the readline interface. Then, create a JSON object with the user inputs and write it to a file using the 'writeFile' method of the fs module.

Step-by-step explanation:

To get inputs from the user in Node.js, you can use the 'readline' module. First, require the module and create a readline interface:



const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});



Next, use the 'question' method of the readline interface to prompt the user for input:



rl.question('Enter your name: ', (name) => {
// do something with the 'name' input
rl.close();
});



Once you have obtained the user inputs, you can create a JSON object with the desired structure:



const user = {
"Name": name,
"Country": country,
"Age": age
};



Finally, you can use the 'fs' module to write the JSON object to a file:



const fs = require('fs');

fs.writeFile('user.json', JSON.stringify([user]), (err) => {
if (err) throw err;
console.log('User data saved.');
});

User Shay Friedman
by
6.9k points