Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File System vs. Path module in Node.js

What are the purposes and differences between these two modules in Node.js? Does one depend on the other?

like image 611
Pazuzu Avatar asked Oct 14 '16 01:10

Pazuzu


People also ask

What is a filesystem node?

The built-in Node. js file system module helps us store, access, and manage data on our operating system. Commonly used features of the fs module include fs. readFile to read data from a file, fs. writeFile to write data to a file and replace the file if it already exists, fs.

What is a file system path?

A path is a string of characters used to uniquely identify a location in a directory structure. It is composed by following the directory tree hierarchy in which components, separated by a delimiting character, represent each directory.

What is a file system module?

The File-System module is part of the System library and provides a generic interface to the file system of the local machine. Remotely mounted file systems are also accessible using this module. Contents. The file-system Module. Types specific to file system operations.

What is __ dirname in node?

In Node. js, __dirname is always the directory in which the currently executing script resides (see this).


1 Answers

What are the purposes and differences between these two modules in Node.js?

The fs module is for actually operating on files, directories and volumes (assuming you have already built an appropriate path for the target). The path module is for manipulating paths which you may then use with the fs module since many fs methods accept a path as an argument.

The fs module contains functions for manipulating files such as:

fs.readFile()
fs.mkdir()
fs.open()
fs.stat()

etc...

The path module contains functions for manipulating file paths such as:

path.join()
path.normalize()
path.extname()
path.parse()

You can read the entire list of functions in each module yourself:

fs module

path module

The descriptions should be pretty obvious what they do.

Does one depend on the other?

Probably not. The fs module assumes you already have a valid path that can be passed right on through to the OS. The path module only builds or parses paths, it doesn't actually do operations on files.

It would be very common to use the two together. For example, you might use the path module to construct a path which you then pass to an fs module function.

like image 176
jfriend00 Avatar answered Nov 15 '22 01:11

jfriend00