如何在加载页面后立即将日志数据附加到文件中?

时间:2012-02-09 14:02:13

标签: javascript node.js

我有一个非常简单的NodeJs脚本,我试图在浏览器中加载页面后立即将一些文本附加到日志文件中。 以下是脚本

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");

我怀疑,我在错误的地方调用了stream.once函数。

我也尝试过这种方式,但我收到了错误

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");

错误:

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)

0 个答案:

没有答案