I literally just found out about Node.js today and I've done so much reading that its making my head hurt. I have the node server up and running. I also have a .JS file on the node server that writes to a text file. I would love to see just one variable (name) get passed from my Javascript application to the server running Node.js so that the Log file gets updated. From what I have read AJAX is the best way to do this. Can someone get me going in the right direction with a small code example on how to do this?
Code of File.js on Server Running Node
var fs = require('fs'), str = 'some text';
fs.open('H://log.txt', 'a', 666, function( e, id )
{
fs.write( id, str + ',', null, 'utf8', function(){
fs.close(id, function(){
console.log('file is updated');
});
}); });
This is how I would do what you mentioned:
Make a quick http server, look at the request variable of any connection, and get the parameters that were passed in, and write that to the file.
var http = require('http');
http.createServer(function (req, res) {
var inputText = req.url.substring(1);
processInput ( inputText );
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Completed.');
}).listen(1337, '127.0.0.1');
Edit here: of course, you still need to define what processInput
is.
function processInput ( text )
{
// What you had before
var fs = require('fs');
fs.open ('H://log.txt', 'a', 666, function (e, id )
{
fs.write ( id, text + ',', null, 'utf8', function() {
fs.close(id, function() {
console.log('file is updated');
}
}
});
}
This way, when you send a request to
127.0.0.1:1337/write
it would write the word "write" into the file (if processInput writes the input).
Another way to process would be with a parameter in the URI. More information on how to do this is found exactly here at the nodejs api.
Good luck!