Save HTML form data to text file using node js

Viewed 767

I am using node js and my requirement is save HTML form values which is sent by user, and store those values in text file using node js, and each time data should be save to next lines instead of saving to same line.I got stuck how to do this process.

HTML Code:

<form method="POST" action="/users/contact"> 

  <select name="car" size="1"  required id="rankx">
    <option value="" selected disabled hidden>Option</option>
    <option value="volvo">volvo</option>
    <option value="swift">swift</option>
  </select>

<br />
  <select name="model" size="1"  required>
    <option value="" selected disabled hidden>Rank</option>
    <option value="c500">c500</option>
    <option value="Ta66">Ta66</option>
  </select>

<input type="submit" value="Submit" name="submit" id="submit"/>

Node js Code:

    var express = require('express');
    var fs = require ('fs');
     
       router.post("/contact",function(req,res){ 
   
    let car = req.body.car;
    let model = req.body.model;
    var form_data = {
        car: car,
        model: model
    }
  fs.appendFileSync('./message.txt',form_data.toString()); 
  }); 

Required outpt: // store in text file userData.txt id carname carmodel 1 abc abc_1 2 xyz xyz_1

1 Answers

The solution what happens to me was first create a JSON file to save the data and next put this information in a text file. Following four steps:

Step 1: First you need read the existing data from JSON file.

Step 2: Add new car using push method.

Step 3: Write the new and old data in JSON file.

Step 4: Write the new info in the a text file.

Here is the code:
app.js

const express = require('express'); 
const app =express()
var fs = require ('fs'); 

// middleware  

app.use(express.urlencoded({extended:true})) 

// STEP 1: Read the existing data from json file  

let users= require("./message.json")

// API routes 

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
  }) 
     
app.post("/",function(req,res){ 
   
    let car = req.body.car;
    let model = req.body.model;
    
    // new car 
    let formData = {
        car: car,
        model: model
    } 

    res.send(formData)  

    // STEP 2: add new user data to users object using push method  
   users.push(formData) 

   // STEP 3: Writing data in a JSON file 

   fs.writeFile('message.json', JSON.stringify(users), err =>{ 
     if(err) throw err 

     console.log("Done writting JSON file")
   }) 

   // STEP 4: Write the new info in the text file named message

  fs.writeFile('./message.txt',JSON.stringify(users), err =>{ 
    if(err) throw err 

    console.log("Done writting text file")
  }); 
  });  

  app.listen(3000, function(){ 
      console.log("server started on port 3000")
  })

You need create a JSON file to save data like this:

message.json

[]

and a empty message.txt to storage the data, this file overwrite when save the data.
Leave screenshots. I hope help you.

Related