将url参数写入文件会导致“undefined”

我刚刚开始与node.js(和整个functioncallback范例),我遇到了一个奇怪的问题。 考虑下面的代码:

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

出于某种原因,我可以写一个string到一个文件,但不是URL参数(这是一个简单的string,没有特殊字符,空格等)的内容。 然而,我可以将这个url参数写入屏幕,没有问题。 进一步testing(并将testing结果写入文件)给了我以下额外的信息:

  • myPackage.toFile(“test”,typeof urlParams); 写下“对象”
  • urlParams不是null或undefined
  • 对于(var我在urlParams)返回没有结果,即使response.write首先被调用

我认为这将是某种asynchronous的东西,我的function被称为太早(而response.write不是,即使它被称为更早),但是我期望urlParams是未定义的,而不是一个对象。

任何人都可以点亮这个?

谢谢!

我也是新来的node.js,但我认为,因为你的数据是一个对象,你可以尝试传递它通过util.inspect()把它变成一个string,如:

 var util = require('util'); ... myPackage.toFile("test", util.inspect(urlParams.data)); 

不知道虽然,试试看,让我们知道。 Console.log自动将对象展平为string,但toFile()可能不会。