Open CheatSheet Back To List Next Tutorial

URL and Path modules (Video Tutorial)

URL and Path modules

Intro

This is the fourth in a series of tutorials on Node.js.

We created a project folder called nodejs-tutorial.
The code for the whole series is available on GitHub at github.com/LearnByCheating/nodejs-tutorial.

If you are following along, open the project in your text editor and create a new folder named 4-path, and create three empty files in it: vars.js, get-path.js, set-path.js

Then open your Terminal application and cd into the new folder.

This tutorial covers the URL and Path modules.

Read it, watch it, do it, review it:
  • There are both a written and accompanying video version of this tutorial. There are timestamps under the headings that align with the video version of the topic.
    • Read it: For each topic heading, first read the topic. 
    • Watch it: Then watch the associated section of the video.
    • Do it: Then follow the instructions to replicate the steps on your computer.
  • The Node.js CheatSheet has a major category that aligns with this tutorial.
    • Review it: When you are done with the whole tutorial, open the CheatSheet and review the URL | Path categories from this tutorial. Make sure you understand everything, and can refer back to the CheatSheet when you are working on your own projects in the future. 



URL Module

[0:00 Video timestamp]

The Node URL module provides utilities for URL resolution and parsing.
It is available on the global object so you don't need to import it before using.


Create a URL object

URL is a class you can use to instantiate a URL object: 
const url = new URL(url string); 

Then access its properties.

Let's see it in action in the Node REPL.
In the Terminal, launch Node:
node

Create a variable named url, set to a new URL object. Pass in a URL string as the argument.
let url = new URL('https://www.example.com/articles/learn-node');

In this example we have a basic URL that includes a path to an article called "Learn node".


URL object properties

The URL string gets parsed into an object with properties for the various parts of the URL. 

You can see all the properties by just entering the variable holding the object:
url

Or access the properties individually by chaining them to the object:
  • url.href - Href holds the full url: https://www.example.com/articles/learn-nod 
  • url.protocol - Protocol is the first part of the url: https
    • http means it uses the hypertext transfer protocol. 
    • https adds a layer of security to it. When using https the data transferred over the internet is encrypted using TLS, Transport Layer Security. 
  • url.hostname - The hostname property includes the www subdomain plus the domain name: www.domainname.com.
  • url.host - The host property is the same as hostname plus the port number if there is one.
  • url.origin - Origin is part of the URL up to the path: https://www/domainname.com.
  • url.path - The path comes after the hostname. It indicates which resource to access on the site: articles/learn-node.

URL Fragment / Hash property
[1:42 Video timestamp]

Now let's add a fragment to the url. Fragments come at the end of the url starting with the pound sign.
That will take you to a location within a web page. The fragment is the id of an element on the page.
In this case it is an element on the learn-node page with the id of "modules":
url = new URL('https://www.example.com/articles/learn-node#modules');

  • url.hash - The hash property returns the fragment: #modules.

URL Query string / Search property
[2:06 Video timestamp]

Query strings also come at the end of the url and start with a question mark followed a key value pair, separated with an equal sign and no spaces. Multiple key-value pairs are separated with the & symbol.
Query strings are often used in search forms.
In this case we are searching for an article with the title learn-node, and author Joey R.
url = new URL('https://www.example.com/articles?title=learn-node&author=Joey+R.');

  • url.search - The search property returns the query string: ?title=learn-node&author=Joey+R. 
  • url.searchParams - searchParams parses the query string into an object: { title: 'learn-node', author: 'Joey R.' }



Path Module

[2:30 Video timestamp]

  • The Node Path module Provides utilities for working with file and directory paths.
  • It is not available on the global object so you do need to import it before using:
const path = require('path');



__dirname and __filename variables

[2:36 Video timestamp]

  • CommonJS has two convenience variables that you can make use of. They start with two underscores:
    • __dirname Gets the absolute path to the current file's directory. 
    • __filename Gets the absolute path to the current file.

To demonstrate this, populate the vars.js file with the below:
nodejs-tutorial/4-path directory/vars.js
console.log(__dirname);
console.log(__filename);

Then in the Terminal execute the file:
node vars

You should see the directory and file paths printed on the screen.



Get path info - parse method

[3:10 and 4:18 Video timestamps]

Now we'll use the path module to get information about a given path.
The parse method takes a path string as the argument, and returns an object with path elements as properties:
path.parse('path'); 
Returns: { root: '/', dir: '/Users/steve/nodeApp', base: 'app.js', ext: '.js', name: 'app' }
  • dir is the path to the file's directory.
  • base is the file name with the extension. 
  • name is the file name without the extension. 
  • ext is the file extension.

Let's see this in action.
Populate the get-path.js file with the below:
nodejs-tutorial/4-path directory/get-path.js
const path = require('path');

const pathString = '/Users/your-username/Documents/nodejs-tutorial/4-path/path-lesson.js';
const pathObj = path.parse(pathString);

  • At the top of the file we are using CommonJS syntax to import the module and set it to a variable named path.
  • The pathString variable is set to an absolute file path.
  • On the last line we used the path parse method to parse the path string into its components and assigned it to the variable pathObj.

In the Terminal, from the nodejs-tutorial/4-path directory launch the Node REPL if it's not already open:
node

Then load the get-path.js file into memory:
.load get-path.js

Now you have access to the path, pathString, and pathObj variables defined in the file. Enter:
pathObj

It will print the path object:
{
  root: '/',
  dir: '/Users/your-username/Documents/nodejs-tutorial/4-path',
  base: 'path-lesson.js',
  ext: '.js',
  name: 'path-lesson'
}

You can get any of the components by chaining the property name to pathObj:
pathObj.root 
pathObj.dir 
pathObj.base 
pathObj.ext
pathObj.name 

Exit Node: Control+D



Create path strings - join and resolve methods

[4:47 and 5:24 Video timestamps]

You can also create path strings with the path module.
There are two methods you can use:
  • path.join([...paths]) Joins path segments into one path string.
  • path.resolve([...paths]) Resolves paths or path segments into an absolute path.

To demonstrate their use, populate the set-path.js file with the below. Replace "steve" with your username:
nodejs-tutorial/4-path directory/set-path.js
const path = require('path');

let pathString = '/Users/steve/Documents/nodejs-tutorial/4-path/path-lesson.js'; console.log(pathString); // Use path.join
pathString = path.join('/', 'Users', 'steve', 'Documents', 'nodejs-tutorial', '4-path', 'path-lesson.js'); console.log(pathString);
pathString = path.join('/Users/steve/Documents/nodejs-tutorial/4-path', 'path-lesson.js'); console.log(pathString); pathString = path.join(__dirname, 'path-lesson.js');
console.log(pathString); // Use path.resolve const otherpath = path.resolve(__dirname, '../2-npm/npm-lesson.js');
console.log(otherpath);

  1. At the top, import the Path module and assign it to variable path.
  2. Set the pathString variable to a string that contains an absolute path.
  3. Reset the variable to the same path, but this time using the path.join method. For the argument, pass in each path segment separated by commas. 
  4. Reset pathString again, also using the path.join method, but this time with the paths combined in the first argument, and the file name in the second.
  5. Reset pathString again, this time for the first segment use the __dirname CommonJS variable to get the absolute path to the current file's directory. Join it with the file name.
  6. Lastly, if you need to derive the path string from a relative path, use the resolve method. 
    • In the first argument we use __dirname to get the directory path of the current file. 
    • The second argument is a relative path from there to the npm-lesson file. ../ takes you up one directory, then the rest of path takes you down to the file.

Execute the file from the Terminal and you will see all the paths are logged:
node set-path

Open CheatSheet Back To List Next Tutorial