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 add, delete, modify and check files in nodejs project

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to add, delete, modify and check files in the nodejs project". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn how to add, delete, modify and check files in the nodejs project.

This paper mainly introduces the file module of nodejs. Through the file module of nodejs, we can create, read, modify and delete files or folders on our operating system, which can also be run on the Linux server. Because nodejs is a cross-platform running environment for javascript.

Project structure: ├── files │ ├── file1 │ └── file2 ├── dir.js ├── index-callback.js ├── index-promise.js └── stream.js regular file operation callback function operation

Create an index-callback.js with the following code

Const fs = require ('fs') const path = require (' path') / / read file fs.readFile (path.join (_ dirname, 'files',' file1'), (err, buf) = > {if (err) throw err console.log (buf.toString ())}) / / write file fs.writeFile (path.join (_ dirname, 'files',' file3'), 'Welcome' (err) = > {if (err) throw err console.log ('write complete') / / append fs.appendFile (path.join (_ _ dirname, 'files',' file3') to the end of the file,'\ n\ n3 male guests' (err) = > {if (err) throw err console.log ('append complete') / / modify the file name fs.rename (path.join (_ _ dirname, 'files',' file3'), path.join (_ _ dirname, 'files',' file3-rename') (err) = > {if (err) throw err console.log ('rename completion')})})

Summary:

ReadFile is used to read the contents of the file. After reading successfully, the callback function returns the buffer format, so you need to call the toString () method.

WriteFile writes to the file, and automatically creates the file if it does not exist.

AppendFile appends content to the end of the file, and automatically creates the file if it does not exist

Rename can be used to modify the file name

Path.join is used to splice file paths to avoid the problem of different path formats in different operating systems.

_ _ dirname is a node.js global variable, and the default is the current project directory

Promise async await operation

Create an index-promise.js with the following code

Const fsPromises = require ('fs'). Promisesconst path = require (' path') const fileFunc = async () = > {try {const data = await fsPromises.readFile (path.join (_ _ dirname, 'files',' file1') console.log (data.toString ()) await fsPromises.unlink (path.join (_ dirname, 'files',' file1') await fsPromises.writeFile (path.join (_ _ dirname, 'files') 'file5'), data) await fsPromises.appendFile (path.join (_ _ dirname,' files', 'file5'),'\ n\ nWelcome') await fsPromises.rename (path.join (_ _ dirname, 'files',' file5'), path.join (_ _ dirname, 'files',' file5-rename') const newData = await fsPromises.readFile (path.join (_ _ dirname, 'files') 'file5-rename')) console.log (newData.toString ())} catch (error) {console.log (error)}} fileFunc ()

Summary:

Compared with callback operation, using async await operation will be more elegant and there will be no callback hell.

Unlink is used to delete files

File stream operation

Create a stream.js with the following code

Method 1: const fs = require ('fs') / / read file stream const rs = fs.createReadStream ('. / files/file2', {encoding: 'utf8'}) / / write file stream const ws = fs.createWriteStream ('. / files/new-file2') / / listen to read and write rs.on ('data', (chunk) = > {ws.write (chunk)})

File stream operation is very useful when reading large files or dealing with network files. When operating large files, we can set the amount of data to be read each time. The default is 64kb.

Method 2 Const fs = require ('fs') / / read file stream const rs = fs.createReadStream ('. / files/file2', {encoding: 'utf8'}) / / write file stream const ws = fs.createWriteStream ('. / files/new-file2') rs.pipe (ws)

The pipe method automatically imports the read file stream into the write stream, which is equivalent to a convenient operation.

Operation folder

Create a dir.js with the following code

Const fs = require ('fs') / / determine whether a folder exists if (! fs.existsSync ('. / new')) {/ / create a folder fs.mkdir ('. / new') (err) = > {if (err) throw err console.log ('folder created successfully')} if (fs.existsSync ('. / new')) {/ / delete folder fs.rmdir ('. / new', (err) = > {if (err) throw err console.log ('folder deleted successfully')})}

Summary:

ExistsSync is a synchronization method used to determine whether a folder exists.

Mkdir create folder

Rmdir delete folder

These three methods of manipulating folders are very common, just like eating every day.

At this point, I believe you have a deeper understanding of "how to add, delete, modify and check files in the nodejs project". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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