Node.js script to capture user input and save the data to a file

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:

  1. 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.
  2. Install required modules: Install the readline module using the following command:
    npm install readline
  3. 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:
    const 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 path
    
    rl.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();
      });
    });
    

     

  4. Run the code: In your terminal, run the following command to execute your Node.js script
    node app.js
    
  5. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top