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: /
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: /
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!");
});
Ok, dividing by parts you have:
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
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>
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.
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
});
});