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 :/
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 :/
3
Okay, divided by parts you have to:
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
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>
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
.
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 javascript html node.js
You are not signed in. Login or sign up in order to post.
Are you using the
expressjs
?– Sergio
No, but if there’s no other way
– MucaP