Processing URL, QueryString and Paths
Processing URL, QueryString and Paths
and Paths
Akash Pundir
System Programming-I
Department of Computer Science and Engineering
https://www.example.com/products?id=123&page=1#overview
What are URLs?
URL stands for Uniform Resource Locator. It is
a reference, or an address used to locate
resources on the internet, such as web
pages, images, documents, and other files.
Ex: https://www.google.com/search?q=Value+of+pi
A typical URL has the following components:
• Protocol: This indicates the protocol used to access the resource, such as
HTTP, HTTPS, FTP, etc.
• Domain: This specifies the domain name or IP address of the server where
the resource is hosted.
• Path: This is the specific location of the resource on the server's file system.
• Query String: This is optional and is used to pass parameters to the
resource. It starts with a question mark (?) and consists of key-value pairs
separated by ampersands (&).
• Fragment: Also optional, this specifies a specific section within the resource,
typically used in HTML documents to navigate to a specific part of a
webpage.
https://www.example.com/products?id=123&
page=1#overview
• Protocol: https://
• Domain: www.example.com
• Path: /products
• Query String: id=123&page=1
• Fragment: overview
Processing URLs:
const url = require('url');
const urlString =
'http://example.com/path?foo=bar&baz=qux';
const parsedUrl = url.parse(urlString,true);
http.createServer((req,res)=>{
let parsedURL=url.parse(req.url,true);
console.log(parsedURL);
console.log(parsedURL.query.name);
if(parsedURL.pathname=='/'){
let readableStream=fs.createReadStream('public/index.html');
readableStream.pipe(res);
}else if(parsedURL.pathname=='/submit' && req.method=="GET"){
let writableStream = fs.createWriteStream('form_data.txt');
let query = parsedURL.query;
writableStream.write(query.name+'\n');
writableStream.write(query.email);
writableStream.on('finish',() => {
console.log("Form has been saved Successfully");
});
writableStream.end();
res.end("Data has been successfully saved");
}
}).listen(4000);