Form for HTML file Node.js

Asked

Viewed 3,444 times

1

Hello! I want a help here: I want when a person writes something in an HTML form, with the node.js, i can save this information in a text file with createFile. I don’t know much about javascript, please help :/

  • Are you using the expressjs?

  • No, but if there’s no other way

2 answers

3

Okay, divided by parts you have to:

  • send the data to the server
  • interpret the data (to avoid writing only a body dump)
  • save to a file

Note that when referring to the function createFile you’re talking about .NET not Node.js. But I’ll assume you want something symmetrical in Node.js

Send data to 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:

Actually I suggest you use the body-parser of express for that and join 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 that the server receives and separate everything right to give to work on Node. Anything passed through the form will be on req.body that with the middleware of the body-parser is an object with keys value of each input, select etc that you have in the <form>. The name element is the key to the property of req.body.

Save to a file:

I suggest you record this to a JSON. The function to use is fs.writeFile, I will give an example of the asynchronous version. The fs.writeFile is native to Node.js but has to be added to 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

    });
});

1


Hello, the answer in English is in https://stackoverflow.com/questions/2496710/writing-files-in-node-js Basically, you will need the lib Fs. Following the code below, Voce can create the file, just receive the HTML information on the Node server and pass 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!");
}); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.