How to append log data into a file as soon as the page is loaded?


#1

I have a very simple NodeJs script in which i am trying to append some text to a log file as soon as the page is loaded in the browser. The following is the script

var http = require('http');
var fs = require('fs');
var stream = fs.createWriteStream("mnodejs.txt");
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
stream.once('open', function(fd){ stream.write("My first row\n"); }) ;
res.end('Hello World\n');
}).listen(8590, "127.0.0.1");

i suspect that , i have called the stream.once function at wrong place .

I also tried this way , but i am getting an error

var http = require('http');
var fs = require('fs');
var log = fs.createWriteStream('nodejs_log.txt', {'flags': 'a'});
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
log.write("this is a message");
res.end('Hello World\n');
}).listen(8590, "127.0.0.1");

error:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: listen EADDRINUSE
    at errnoException (net.js:632:11)
    at Array.0 (net.js:733:26)
    at EventEmitter._tickCallback (node.js:192:40)