Im trying to understand if I can get node to read an html file (test.html) and then asynchronously write a users input to the same file via a text input. I've set up my web server on webserver.js, and then set up another page named test.html.
I have added listeners to my 'test' case in the switch, to listen for data, log data to the servers terminal, and then (i assume) write this data to the file.
I understand that there is no direct connection from the webserver.js script to the input field on test.html, which might be my first problem. Secondly, I'm aware that there is no defined area on test.html to render the response. This is something I'd like to know how to do in Node.
So I'm hoping I can get a bit of guidance on how I could get this to work, if its not too much trouble.
var http = require('http')
, url = require('url')
, fs = require('fs')
, server;
server = http.createServer(function(req, res){
var path = url.parse(req.url).pathname;
var userData = "";
switch(path){
case '/':
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) throw err;
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data, 'utf8');
res.end();
});
case '/test':
fs.readFile(__dirname + '/test.html', function (err, data) {
if (err) throw err;
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data, 'utf8');
req.addListener("data", function(userDataChunk) {
userData += userDataChunk;
console.log("Received chunk ’"+userDataChunk + "’.");
res.end("<p>" + userData + "</p>");
});
});
break;
default: '/';
}
});
and on test.html I just have a text input
<html>
<head></head>
<body>
<input type="text" name="userInput" />
</body>
</html>
I know that I could just add some javascript on the test.html to take the input on keyup and write it to the page, but I'm just wondering if this can all be done with Node.js?
Any help is appreciated, thanks.