patidar patidar - 6 months ago 10
Node.js Question

Writing input into output text in Node js

I am fairly new with node js. Right now I am running a web server where the client has to type their name in and a profile is made. However, I want the name the client typed to be written to an output.txt file. I know how to write hello world to an output text but not how to get a client's input to be directly written into an output text file.

var http = require('http');
var postHTML =
'<html><head><title>Post Example</title></head>' +
'<body>' +
'<form method="post">' +
'Input 1: <input name="input1"><br>' +
'Input 2: <input name="input2"><br>' +
'<input type="submit">' +
'</form>' +
'</body></html>';

http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
console.log('POSTed: ' + body);
res.writeHead(200);
res.end(postHTML);
});
}).listen(8080);


I want whatever the user types to input 1 to be saved to an output file

Answer

@patidar I am very new to node and I just made a solution. It may not give you the correct answer but an approach to proceed.

Hope this helps:

 var http = require('http');
 var qs = require('querystring');
 var fs = require('fs');
    var postHTML = 
    '<html><head><title>Post Example</title></head>' +
    '<body>' +
    '<form method="post">' +
    'Input 1: <input name="input1"><br>' +
    'Input 2: <input name="input2"><br>' +
    '<input type="submit">' +
    '</form>' +
    '</body></html>';

    http.createServer(function (req, res) {
     var body = "";
       req.on('data', function (chunk) {
      body += chunk;

      console.log(body);
      });
     req.on('end', function () {
       console.log('POSTed: ' + body);
       var post = qs.parse(body);
       console.log(post.input1);
       fs.writeFile("result_posted.txt",post.input1);
      res.writeHead(200);
     res.end(postHTML);
      });
    }).listen(8080);

It is writing the data into the file, but the problem is your code is posting the data twice so it is getting overwrited.

If anybody want to edit the post feel free to edit. Thanks.