Node.js: Using built-in modules

Node comes with many built-in modules.

For example, we can access the filesystem of the computer using simple functions offered by the Node built-in modules fs, path, and os.

We’re going to try that now, so we’ll have a first encounter with using Node.

The fs module provides a lot of very useful functionality to access and interact with the file system.

There is no need to install it.

Being part of the Node core, it can be used by importing it:

import fs from 'fs'

NOTE: as explained in the ES Modules unit, remember to rename the file to .mjs or create a package.json file in the project folder, and add this content:

{
  "type": "module"
}

The particular thing about being built-in is that we don’t have to install these modules as we did for 3rd party node modules, we just require it and we have access to the functionality it provides.

Once you do so, you have access to all its methods, which include:

  • fs.copyFile(): copies a file
  • fs.mkdir(): create a new folder
  • fs.readFile(): read the content of a file
  • fs.rename(): rename a file or folder
  • fs.rmdir(): remove a folder
  • …and many more.

Let’s try.

Create a file.txt file with some random content, and save this Node.js program in index.js.

import fs from 'fs'

fs.rename('file.txt', 'newname.txt', (err) => {
  if (err) {
		//oops there's been an error renaming!
    console.error(err)
		return
  }

  //the file has been renamed!
})

Run this using node index.js and the file.txt file should be renamed to newname.txt!

This would be impossible inside the browser.

JavaScript (fortunately!) has no access to files on the computer, otherwise, it’d be a security risk.

But Node.js programs can access the filesystem, because when you run a Node program, you know (or should know) what you are doing.

It’s not like the program runs automatically when you visit a random website.

For example, I sometimes write Node.js programs to mass rename files or do other things.

Lessons in this unit:

0: Introduction
1: Installing Node.js on your computer
2: How to write your first Node.js program
3: Importing other files
4: Using npm to install packages
5: ▶︎ Using built-in modules
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!