2012-12-16 62 views
2

我剛剛開始使用node.js(以及整個函數回調範例),並且遇到了一個奇怪的問題。請看下面的代碼:將url參數寫入文件導致「未定義」

var http = require("http"); 
var myPackage = require("./myPackage.js"); //Custom package 

http.createServer(function(request, response) 
{ 
    request.on("end", function() 
    { 
     //This custom package method retrieves the GET params from the URL 
     //and then calls the callback with the params object as argument 
     myPackage.getUrlParams(request, function(urlParams) 
     { 
      response.writeHead(200, {"Content-Type": "text/plain"}); 

      //This works - it shows me the content of the "data" url parameter, 
      //so myPackage.getUrlParams works fine 
      response.write("data: " + urlParams.data + ". "); 

      //This does not work - the test file is created with the right 
      //extension in the right place (handled by myPackage) but the 
      //content is "undefined" 
      myPackage.toFile("test", urlParams.data); 

      //This works - so myPackage.toFile seems to be fine 
      myPackage.toFile("test", "Hello World"); 

      //This obviously works fine 
      response.end("Done."); 
     }); 
    }); 
}).listen(8080); 

出於某種原因,我可以寫一個字符串到一個文件,而不是URL參數的內容(這是一個簡單的字符串,沒有特殊字符,空格等)。然而,我可以將這個url參數寫入屏幕,沒有問題。進一步測試(並將測試結果寫入文件)給了我以下額外信息:

  • myPackage.toFile(「test」,typeof urlParams);寫到遠「對象」
  • urlParams不爲空或(VAR我在urlParams)不返回任何結果不確定
  • ,即使回覆於被稱爲第一

我認爲這將是某種異步的東西,我的功能被稱爲太早(而response.write不是,即使它被稱爲更早),但是我希望urlParams是未定義的,而不是一個對象。

任何人都可以對此有所瞭解嗎?

謝謝!

回答

1

我也是新的node.js,但我想是因爲你的數據是一個對象,你可以嘗試將其通過util.inspect()把它變成一個字符串,如:

var util = require('util'); 

... 

myPackage.toFile("test", util.inspect(urlParams.data)); 

不知道不過,試試看,讓我們知道。 Console.log自動將對象壓扁爲字符串,但toFile()可能不會。

+1

這似乎是它。實際上,我只是嘗試了urlParams.data.toString(),並且不需要使用util。謝謝!我會在一會兒接受你的回答(我似乎需要等待幾分鐘才能接受)。 – WebStakker