私は 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("テスト", typeof urlParams); 「オブジェクト」を書き留めます
- urlParams が null または未定義ではない
- for (var i in urlParams) は、response.write が最初に呼び出されたにもかかわらず、結果を返しません。
これは、関数が呼び出されるのが早すぎる非同期のようなものだと思っていましたが (response.write は、以前に呼び出されたとしてもそうではありません)、urlParams は未定義であり、オブジェクトではないと予想されます。
誰でもこれに光を当てることができますか?
ありがとう!