How Execute A Javascript In A Node.js Server
I have written a node.js server. I am able to extract the HTTP POST and GET variable from the request. I would like to pass those variable to the js script on the server to be exec
Solution 1:
Lets say you have a URL parameter named variable
. I think this would work:
var parameters = url.parse(request.url, true);
var variable = parameters.variable;
I haven't used node.js in a while, but I'm pretty sure this works.
Solution 2:
I don’t know what your code chunk is supposed to do, but here is a basic Hello World for you that prints out a get parameter:
var http = require('http');
var url = require('url');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
var params = url.parse(request.url, true);
response.end("You have " + params.query.variable);
});
server.listen(8000);
Now just visit 127.0.0.1:8000/?variable=foo
Solution 3:
In summary what I wanted to achieve is use node.js like PHP.
to execute a PHP file like
www.example.com/path/file.php?variable=value
With node.js
www.example.com/path/file.js?variable=value
The solution I have come up with is to make the requested javascript into a module and include it with the function require
.
e.g.
http.createServer(function(req,res){
var myPath=url.parse(req.url).pathname;//get the urlvar fullPath=path.join(process.cwd(),myPath);//get the working dir & join it with current working dirrequire(fullPath).content(req,res);//this is where the requested script is executed as a module. make sure to end the response (response.end()) in the module
});
Though not thoroughly tested this solution works for me and I can use it even for dynamic pages.
Post a Comment for "How Execute A Javascript In A Node.js Server"