Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Get Path from the Request

We can get the path from the request by using the request.url to get parse the request URL.

For instance, we can write:

const http = require("http");
const url = require("url");

const onRequest = (request, response) => {
  const pathname = url.parse(request.url).pathname;
  console.log(pathname);
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.write("hello");
  response.end();
}
http.createServer(onRequest).listen(8888);

All we have to do is to get the request.url property to get the URL.

Then we can parse it with the url module.

We can then get the pathname to get the relative path.

Convert Relative Path to Absolute

We can convert a relative path to an absolute path by using the path module’s resolve method.

For example, we can write:

const resolve = require('path').resolve
const absPath = resolve('../../foo/bar.txt');

We call resolve with a relative path to return the absolute path of the file.

#web-development #programming #javascript #technology #software-development

Node.js Tips — Request URLs, Parsing Request Bodies, Upload
1.20 GEEK