node.js-fs, path module


Js, DOM, BOM and Browser

Each browser has APIs connected to DOM and BOM objects on the pages so that Js could use them to operate on DOM and BOM:

JS Environment in Chrome Browser:

JS Environment in Node.js:

fs Module

fs.readFile()

method parameters (default format is UTF-8):

example: read file in UTF-8 format, print error(if successful, error == null) or data:

fs.write()

fs.write can only create file can’t create directory

method parameters:

example:

Combined Example

read data in a file, edit and store them in a new file:

Relative Path Problem

in node.js, the relative path is positioned via the directory where the node command is executed but not the directory of the executed Js file:

image-20220922141154423

__dirname

in node.js, __dirname is a variable stores the absolute path of the current Js file:

Use __dirname to solve the relative path problem:

Path Module

path.join(): join multiple path string into a complete path string

path.basename(): return filename string from a path string

path.join()

use path.join() to replace + because the method could resolve ‘./‘ and ‘../‘ in path name

method parameters:

example(attention to ‘../‘ and ‘./‘):

path.basename()

method parameters:

example:

path.extname

method parameters:

example:


A u t h o r: Joe
P o l i c y: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source Joe !
Leave Your Comment Here
  TOC