Capturing user input and storing it in a file using Node.js involves a few steps. You can use the built-in fs
(file system) module to interact with files and the readline
module to capture user input. Here’s a simple example:
- Create a new Node.js project: If you haven’t already, create a new directory for your project, navigate to it in your terminal, and initialize a new Node.js project by running
npm init
. - Install required modules: Install the
readline
module using the following command:
1npm install readline - Write the code: Create a JavaScript file (e.g.,
app.js
) and add the following code to capture user input and store it in a file:
1234567891011121314151617181920const fs = require('fs');const readline = require('readline');const rl = readline.createInterface({input: process.stdin,output: process.stdout});const filePath = 'user_input.txt'; // Change this to your desired file pathrl.question('Enter some text: ', (inputText) => {fs.appendFile(filePath, inputText + '\n', (err) => {if (err) {console.error('Error writing to file:', err);} else {console.log('Input saved to file successfully.');}rl.close();});});
- Run the code: In your terminal, run the following command to execute your Node.js script
1node app.js - Provide input: When you run the script, it will prompt you to enter some text. After you enter the text and press Enter, the text will be stored in the specified file (user_input.txt in this case).
This example uses the fs.appendFile() method to add a new input to the file without overwriting existing content. If you want to replace the content every time you capture input, you can use fs.writeFile() instead. Just be cautious when using writeFile because it will erase the existing content of the file.
Hope this post helps you to write a simple node.js script to get the user input and store the data in a file.