0

我也是 node.js 的新手,并通过教程来了解基础知识

sys = require("sys");  
var http = require("http");  
var url = require("url");
var fs=require("fs");

http.createServer(function(request,response){  
    sys.puts("I got kicked");   
    //var _get = url.parse(request.url, true).query;
    request.on("end", function () {

      fs.readFile("test.txt", 'utf-8', function (error, data) {
         // Write headers.
         response.writeHead(200, {'Content-Type': 'text/plain'});
         // Increment the number obtained from file.
         data = parseInt(data) + 1;
         // Write incremented number to file.
         fs.writeFile('test.txt', data);
         // End response with some nice message.
        response.end('This page was refreshed ' + data + ' times!'); 
      });

   });

    //response.write("Hello World");  
    //response.end('Here is your data: ' + _get['data']);  
}).listen(8080);  
sys.puts("Server Running on 8080");

从http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/获得此代码, 但它不起作用,我从浏览器收到“未收到数据”错误。严重痴迷我想知道它有什么问题。如果我将 response.end() 放在 request.on() 之外,它会起作用,但不会识别数据对象......帮助!

4

2 回答 2

2

您不想使用request.on但确实想放入response.end回调readFile,否则它将在数据被读出之前返回:

var sys = require("sys");
var http = require("http");
var url = require("url");
var fs=require("fs");

http.createServer(function(request,response){
    sys.puts("I got kicked");
    //var _get = url.parse(request.url, true).query;
    fs.readFile("test.txt", 'utf-8', function (error, data) {
       // Write headers.
       response.writeHead(200, {'Content-Type': 'text/plain'});
       // Increment the number obtained from file.
       data = parseInt(data) + 1;
       // Write incremented number to file.
       fs.writeFile('test.txt', data);
       // End response with some nice message.
       response.end('This page was refreshed ' + data + ' times!');
    });

}).listen(8080);
sys.puts("Server Running on 8080");

正如@chris 所指出的,您的计数器每次都会增加 2。

于 2013-07-27T17:42:55.620 回答
0

只是你一开始并没有任何文件。

http://pastebin.com/M5verL8w

顺便说一句,由于 favicon.ico 请求,您将获得 2 次刷新

(顺便说一句,我没有收到您提到的错误。您使用的是什么 node.js 版本?)

更新:好的,我做了一些编辑,现在检查一下

于 2013-07-27T17:35:10.253 回答