Node.js: get path from the request

Javascriptnode.jsExpress

Javascript Problem Overview


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);
});
};

Javascript Solutions


Solution 1 - Javascript

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/

Solution 2 - Javascript

simply call req.url. that should do the work. you'll get something like /something?bla=foo

Solution 3 - Javascript

You can use this in app.js file .

var apiurl = express.Router();
apiurl.use(function(req, res, next) {
	var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
	next();
});
app.use('/', apiurl);

Solution 4 - Javascript

req.protocol + '://' + req.get('host') + req.originalUrl

or

req.protocol + '://' + req.headers.host + req.originalUrl // I like this one as it survives from proxy server, getting the original host name

Solution 5 - Javascript

Based on @epegzz suggestion for the regex.

( url ) => {
  return url.match('^[^?]*')[0].split('/').slice(1)
}

returns an array with paths.

Solution 6 - Javascript

A more modern solution that utilises the URL WebAPI:

(req, res) => {
  const { pathname } = new URL(req.url || '', `https://${req.headers.host}`)
}

Solution 7 - Javascript

I've used this const { pathname } = req?._parsedUrl || {}; and it worked for me

Solution 8 - Javascript

Combining solutions above when using express request:

let url=url.parse(req.originalUrl);
let page = url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '';

this will handle all cases like

localhost/page
localhost:3000/page/
/page?item_id=1
localhost:3000/
localhost/

etc. Some examples:

> urls
[ 'http://localhost/page',  'http://localhost:3000/page/',  'http://localhost/page?item_id=1',  'http://localhost/',  'http://localhost:3000/',  'http://localhost/',  'http://localhost:3000/page#item_id=2',  'http://localhost:3000/page?item_id=2#3',  'http://localhost',  'http://localhost:3000' ]
> urls.map(uri => url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '' )
[ 'page', 'page', 'page', '', '', '', 'page', 'page', '', '' ]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNabil DjarallahView Question on Stackoverflow
Solution 1 - JavascriptGauravView Answer on Stackoverflow
Solution 2 - JavascriptSagiv OfekView Answer on Stackoverflow
Solution 3 - Javascriptkumbhani bhaveshView Answer on Stackoverflow
Solution 4 - JavascriptXinView Answer on Stackoverflow
Solution 5 - JavascriptIdeabileView Answer on Stackoverflow
Solution 6 - JavascriptkanoView Answer on Stackoverflow
Solution 7 - JavascriptMisticoView Answer on Stackoverflow
Solution 8 - JavascriptloretoparisiView Answer on Stackoverflow