Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
write/add data in file using express js

I'm trying to write/add data in a json file (for example for each request, a new json is added in the json file) i am using Express.js. I am new to all of this so I really don't know what to do. I'm using a POST request, here's what i got so far. I know it's a big catastrophic mess, i scraped everything that could help me and gathered all of it. I'm just SO lost. Thanks for your help !

app.post('*/', function(req, res) {
  res={
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    reponse1: req.body.reponse1,
    reponse2: req.body.reponse2,
  };
  JSON.stringify(res);
  var body =  {
  table: []
  }; 
  body.table.push(res);
  filePath = __dirname + '/data.json';
  req.on('data', function(data) {
     body += data;
  });

  req.on('end', function (){
    fs.appendFile(filePath, body, function() {
         res.end();
    });
});

});

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

In your code, I see a lot of bugs. Firstly, you should not assign res = { }. Secondly, you stringify the JSON data like below. I will also suggest you to go through some tutorials of Node.js first. You can go through https://www.tutorialspoint.com/nodejs/ or https://www.codementor.io/nodejs/tutorial.

For your requirement, you can simply use following code:

const express 	= require('express')
const app     	= express()
const bodyParser= require('body-parser')
const fs 		= require('fs')


app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

app.post('/', function(req, res){
	var body = {
	    first_name: req.body.firstName,
	    last_name: req.body.lastName
	}
	filePath = __dirname + '/data.json'

	fs.appendFile(filePath, JSON.stringify(body), function(err) {
		if (err) { throw err }
		res.status(200).json({
			message: "File successfully written"
		})
    })

})

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!