Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use path module and fs module in node

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to use the path module and fs module in node". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Path module

The path module is used to process paths and files and provides many methods.

Path.resolve

One requirement is to concatenate the path and the file name.

Const basePath ='/ user/why'const filename = 'abc.txt'

Then someone will use string concatenation for splicing.

Const filePath = basePath +'/'+ filenameconsole.log (filePath)

There is no problem with this result, but considering different systems, windows systems can use\ or\ or / as the path separator, while the Unix operating systems of Mac OS and Linux use / as the path separator.

To solve the above problems, we can use path.resolve for path stitching.

Const path = require ('path') const basePath =' / user/why'const filename = 'abc.txt'const filePath = path.resolve (basePath, filename) console.log (filePath)

Get information from the path

Dirname: get the parent folder of the file

Basename: get the file name

Extname: get the file extension

Const path = require ('path') const filePath =' / User//abc.txt'console.log (path.dirname (filePath)); console.log (path.basename (filePath)); console.log (path.extname (filePath))

Path splicing

If we want to concatenate multiple paths, but different operating systems may use different delimiters, we can use the path.join function.

Const path = require ('path') const basepath =' / User/'const filename = 'abc.txt'const filePath = path.join (basepath, filename) console.log (filePath)

Splice a file with a folder

If we want to concatenate a file and folder, we can use path.resolve.

Const basepath = 'User/'const filename =' abc.txt'

Path.resolve can stitch paths just like path.join, so what's the difference between them?

Const basepath ='.. / User/'const filename ='. / abc.txt'const othername ='. / .js'const filePath2 = path.join (basepath, filename, othername) console.log (filePath2); const filePath3 = path.resolve (basepath, filename, othername) console.log (filePath3)

We can see the difference between them.

Fs module

The API of nodejs file system mostly provides three modes of operation:

Synchronization operation file: the code will be blocked and will not continue execution

Asynchronous callback function operation file: the code will not be blocked and the callback function needs to be passed in. When the result is obtained, the callback function executes

Asynchronous Promise operation file: the code will not be blocked. If a method operation is called through fs.promises, a Promise will be returned, which can be processed through then and catch.

Read file status (information)

Method 1 synchronous operation: fs.statSync

Const fs = require ('fs') const filepath ='. / abc.txt'const info = fs.statSync (filepath) console.log ('code to be executed later'); console.log (info)

Mode 2 asynchronous operation

Fs.stat (filepath, (err, info) = > {if (err) {console.log (err); return} console.log (info); console.log (info.isFile ()); / / determine whether it is a file console.log (info.isDirectory ()); / / determine whether it is a folder}) console.log ('code to be executed later')

Method 3: Promise

Fs.promises.stat (filepath) .then (info = > {console.log (info);}) .catch (err = > {console.log (err);}) console.log ('code to be executed later'); file descriptor

Node assigns a numeric file descriptor to all open files. All file system operations use these file descriptors to identify and track each specific file.

The fs.open () method is used to assign a new file descriptor, FD. Once assigned, the file descriptor can be used to read data from the file, write data to the file, or request information about the file.

Const fs = require ('fs') fs.open ('. / abc.txt', (err, fd) = > {if (err) {console.log (err); return} / / get the file information fs.fstat (fd, (err, info) = > {console.log (info);})}) File read and write through the file descriptor

Fs.readFile (path [, options], callback): read file contents

Fs.writeFile (path [, options], callback): writes to a file

Option parameters:

Flag: how to write

Encoding: encoding of characters

Writing of files

Fs.writeFile ('. / abc.txt', content, {flag: "a"}, err = > {console.log (err);})

Reading of files

Fs.readFile ('. / abc.txt', (err, data) = > {console.log (data);})

If you do not enter encoding, the result returned is Buffer (binary).

Fs.readFile ('. / abc.txt', {encoding: 'utf-8'}, (err, data) = > {console.log (data);})

Create a folder

Create a new folder using fs.mkdir () or fs.mkdirSync.

Const fs = require ('fs') / / create folder const dirname ='. / 'if (! fs.existsSync (dirname)) {fs.mkdir (dirname, (err) = > {console.log (err);})} get the contents of the folder

Fs.readdir

Fs.readdir (dirname, (err, files) = > {console.log (files);})

Get all the files in the folder, where the directory is shown below, and you can use recursion.

Const fs = require ('fs') const path = require (' path') const dirname ='. / 'function getFiles (dirname) {fs.readdir (dirname, {withFileTypes: true}, (err, files) = > {/ / console.log (files) For (let file of files) {/ / determine whether it is a folder if (file.isDirectory ()) {const filepath = path.resolve (dirname, file.name) getFiles (filepath)} else {console.log (file.name);} getFiles (dirname) rename

You can use fs.rename to rename folders.

Fs.rename ('. / ','. / xixi', err = > {console.log (err);}) "how to use the path module and fs module in node" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report