Form for HTML file Node.js

1

Hello! I want a help here: I want when someone writes something in an HTML form, with node.js , I can save this information in a text file with createFile. I do not know much about javascript, please help: /

    
asked by anonymous 18.09.2015 / 22:07

2 answers

1

Hello, the response in English is at link Basically, you'll need lib fs. Following the code below, you can create the file, just receive the HTML information on the server node and go to the second parameter.

// -------------------------

var fs = require('fs');
fs.writeFile("/pasta/test", "Criando novo arquivo!", function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("o arquivo foi gravado!");
}); 
    
09.10.2015 / 19:24
1

Ok, dividing by parts you have:

  • send the data to the server
  • interpret the data (to avoid writing a dump of the body)
  • write to a file

Note that when you refer to the function createFile are you talking about .NET and not Node.js. But I'll assume you want something similar in Node.js

Send the data to the server:

This part is done on the client side. In its simplest way it is only with HTML but there are other ways, using ajax. But in the simplest version you have a form like this:

<form action="/dados-formulario" method="post">
      <input type="text" name="username">
      <input type="password" name="password">
      <input type="submit" value="Log In">
</form>

Interpret the data on the server:

I actually suggest you use body-parser from express for this and put it together as middleware:

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

What this plugin / middleware does is convert the text the server receives and separate everything right to give it to work on the Node. Anything passed through the form will be in req.body , which with the middleware of body-parser is an object with value keys of every input , select etc that you have in <form> . The name of the element is the key of the req.body property.

Save to a file:

I suggest you write this down in a JSON. The function to use is fs.writeFile , I'll give an example of the asynchronous version. The fs.writeFile is native to Node.js but must be added to the code.

app.post('/dados-formulario', function(req, res){
    var conteudo = JSON.stringify(req.body);
    var fs = require('fs');
    fs.writeFile('nome-do-ficheiro.txt', conteudo, 'utf8', function (err) {
      if (err) throw err;
      // correr código aqui depois do ficheiro estar gravado

    });
});
    
09.10.2015 / 20:03