I have a service called "localhost:3000/returnStat" that should take a file path as parameter. For example '/BackupFolder/toto/tata/titi/myfile.txt'.
How can I test this service on my browser? How can I format this request using Express for instance?
exports.returnStat = function(req, res) { var fs = require('fs'); var neededstats = []; var p = __dirname + '/' + req.params.filepath; fs.stat(p, function(err, stats) { if (err) { throw err; } neededstats.push(stats.mtime); neededstats.push(stats.size); res.send(neededstats); }); };
We can get the path of the present script in node. js by using __dirname and __filename module scope variables. __dirname: It returns the directory name of the current module in which the current script is located. __filename: It returns the file name of the current module.
__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.
The path. basename() method returns the filename part of a file path.
var http = require('http'); var url = require('url'); var fs = require('fs'); var neededstats = []; http.createServer(function(req, res) { if (req.url == '/index.html' || req.url == '/') { fs.readFile('./index.html', function(err, data) { res.end(data); }); } else { var p = __dirname + '/' + req.params.filepath; fs.stat(p, function(err, stats) { if (err) { throw err; } neededstats.push(stats.mtime); neededstats.push(stats.size); res.send(neededstats); }); } }).listen(8080, '0.0.0.0'); console.log('Server running.');
I have not tested your code but other things works
If you want to get the path info from request url
var url_parts = url.parse(req.url); console.log(url_parts); console.log(url_parts.pathname);
1.If you are getting the URL parameters still not able to read the file just correct your file path in my example. If you place index.html in same directory as server code it would work...
2.if you have big folder structure that you want to host using node then I would advise you to use some framework like expressjs
If you want raw solution to file path
var http = require("http"); var url = require("url"); function start() { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + " received."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
source : http://www.nodebeginner.org/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With