I’m just starting with node.js (and with the whole functional callback paradigm) and I’m running into a strange issue. Consider the following code:
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);
For some reason, I can write a string to a file, but not the content of the url parameter (which is a simple string, no special characters, spaces, etc). Yet, I can write that url parameter to the screen without problem. Further testing (and writing the test results to the file) gave me the following extra information:
- myPackage.toFile(“test”, typeof urlParams); writes away “object”
- urlParams is not null or undefined
- for (var i in urlParams) returns no results, even though the response.write is called first
I thought this would be some kind of asynchronous thing where my function is called too early (whereas response.write is not, even though it’s called earlier), but then I’d expect urlParams to be undefined and not an object.
Can anyone shed some light on this?
Thanks!
I’m also new to node.js but I think because your data is an object, you could try passing it through
util.inspect()to turn it to a string, like:Not sure though, give it a try and let us know.
Console.logautomatically flattens objects to strings, buttoFile()maybe does not.