我刚从 node.js 开始(以及整个功能回调范例),我遇到了一个奇怪的问题。考虑以下代码:
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 不为 null 或未定义
- for (var i in urlParams) 不返回任何结果,即使首先调用 response.write
我认为这将是某种异步的事情,其中我的函数被调用得太早(而 response.write 不是,即使它被更早地调用),但我希望 urlParams 是未定义的,而不是一个对象。
任何人都可以对此有所了解吗?
谢谢!