node legacy url.parse deprecated, what to use instead?
Javascriptnode.jsUrlJavascript Problem Overview
require('url').parse('someurl.com/page')
have been docs-only deprecated, and our strict linter is unhappy about it... I have tried to replace it in our code with what the internet suggests new URL('someurl.com/page')
which works in most cases.
However, we have examples where the url is a local image some/image.png
and that was working nicely with url.parse() and returns:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/some/image.png',
path: '/some/image.png',
href: '/some/image.png'
}
But the suggested replacement new URL('some/image.png')
throws a type error...
> TypeError [ERR_INVALID_URL] [ERR_INVALID_URL]: Invalid URL: > /some/image.png
url.parse is doing some validation and accept local paths, but the new url constructor does not. What to do ?
Javascript Solutions
Solution 1 - Javascript
const server = http.createServer((req, res) => {
const baseURL = req.protocol + '://' + req.headers.host + '/';
const reqUrl = new URL(req.url,baseURL);
console.log(reqUrl);
});
will give reqUrl :
URL {
href: 'http://127.0.0.1:3000/favicon.ico',
origin: 'http://127.0.0.1:3000',
protocol: 'http:',
username: '',
password: '',
host: '127.0.0.1:3000',
hostname: '127.0.0.1',
port: '3000',
pathname: '/favicon.ico',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
Solution 2 - Javascript
You can use the base parameter of the URL constructor. For example:
new URL('some/image-png', "https://dummyurl.com")
For more info, https://nodejs.org/api/url.html#url_constructor_new_url_input_base.
Solution 3 - Javascript
const path = require("path");
const url = require("url");
const p = path.join("public", "images", "a.jpg");
console.log(p); // public\images\a.jpg
console.log(new url.URL(p, "http://xxx").pathname); // /public/images/a.jpg
Solution 4 - Javascript
This is how to get the query string params without using any external modules
const http = require("http");
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host}/`);
const query = new URLSearchParams(url.search);
console.log(query.entries());
res.end("I am done");
});
server.listen(3000);