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 the fs module of Nodejs

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

Share

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

In this article Xiaobian for you to introduce in detail "how to use the fs module of Nodejs", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to use the fs module of Nodejs" can help you solve your doubts.

The use of fs module in Nodejs 1, fs.stat check whether it is a file or a directory

Const fs = require ('fs') fs.stat ('. / html', (err, data) = > {if (err) {console.log (err) return} console.log (`is a file: ${data.isFile ()}`) console.log (`is a directory: ${data.isDirectory ()}`) fs.stat ('. / package.json', (err) Data) = > {if (err) {console.log (err) return} console.log (`is file: ${data.isFile ()}`) console.log (`is directory: ${data.isDirectory ()}`)})

2. Create a directory by fs.mkdir

The original catalog

Const fs = require ('fs') / * the directory path that path will create mode directory permissions (read and write permissions). Default is 777 callback callback, passing exception parameter err * / fs.mkdir ('. / css', (err) = > {if (err) {console.log (err) return} console.log ('created successfully'))

After the code is executed

Execute the code again, indicating that it has been created

3. Fs.writeFile creates a write file

Const fs = require ('fs') / * filename (String) file name data (String | Buffer) what will be written, can make a string or buffer data. Options (Object) option array object, containing: encoding (string) optional value, default 'utf8', when data makes buffer, this value should be ignored. Read and write permissions for mode (Number) files. Default is 438 flag (String). Default is'w' callback {Function} callback, passing an exception parameter err. * / fs.writeFile ('. / html/index.html', 'Hello nodejs', (err) = > {if (err) {console.log (err) return} console.log (' write file created successfully'))

If the write is repeated, the content will be replaced

4. Fs.appendFile appends files

Const fs = require ('fs') fs.appendFile ('. / css/base.css', 'body {color:red}', (err) = > {if (err) {console.log (err); return;} console.log ('appendFile successful');})

After the code is executed

If the code is executed repeatedly, it will be appended and will not be replaced

5. Fs.readFile reads the file const fs = require ('fs') fs.readFile ('. / html/index.html', (err, data) = > {if (err) {console.log (err); return;} console.log (data) console.log (data.toString ()) / / convert Buffer to string type})

6. Fs.readdir read directory const fs = require ('fs') fs.readdir ('. / html', (err, data) = > {if (err) {console.log (err); return;} console.log (data)})

7. Rename fs.rename

Function: 1. Rename 2. Move files.

Const fs = require ('fs') fs.rename ('. / css/base.css','. / css/index.css', (err) = > {if (err) {console.log (err); return;} console.log ('renamed successfully)})

After the code is executed

Take another look at how to use mobile files.

Const fs = require ('fs') fs.rename ('. / css/index.css','. / html/index.css', (err) = > {if (err) {console.log (err); return;} console.log ('file moved successfully'))

After the code is executed

8. Fs.rmdir deletes a directory

Const fs = require ('fs') fs.rmdir ('. / html/aaa', (err) = > {if (err) {console.log (err); return;} console.log ('directory deleted successfully'))

After the code is executed

Look at another example.

Const fs = require ('fs') fs.rmdir ('. / html/aaa', (err) = > {if (err) {console.log (err); return;} console.log ('directory deleted successfully'))

After executing the code, I found that the aaa directory was not deleted, but an error was reported because

Note that if there are files in this directory, you need to delete the files before deleting the directory.

9. Fs.unlink deletes files

Const fs = require ('fs') fs.unlink ('. / html/aaa/aaa.html', (err) = > {if (err) {console.log (err); return;} console.log ('file deleted successfully'))

After the code is executed

10. Third-party mkdirp

Const mkdirp = require ('mkdirp') mkdirp ('. / upload/aaa/bbb'). Then (made = > console.log (`made directories, starting with ${made} `))

After the code is executed

11. Comprehensive exercises

1. Determine if there is a upload directory on the server. If you haven't created this directory, don't do it if you have one.

/ / 1. Determine if there is a upload directory on the server. If you haven't created this directory, don't do it if you have one. Const fs = require ('fs') const path ='. / upload'fs.stat (path, (err, data) = > {if (err) {/ / does not have this directory, execute create directory mkDir (path)} if (data.isDirectory ()) {console.log ('failed to create, already have this directory')} else {/ / does not have this directory, if there is a file with the same name After you need to delete this file Then create the directory fs.unlink (path, (err) = > {if (! err) {mkDir (path)} else {console.log ('check whether the incoming data is correct')})}) function mkDir (path) {fs.mkdir (path, (err) = > {if (err) {console.log (err) return}})})}

After the code is executed

2. Exercise: there are images css js and index.html under the wwwroot folder. Find all the directories under the wwwroot directory and put them in an array.

There are images css js and index.html under the / / wwwroot folder. Find all the directories under the wwwroot directory and put them in an array const fs = require ('fs'); / / incorrect spelling Note: the method in fs is asynchronous / * var path ='. / wwwroot';var dirArr = []; fs.readdir (path, (err, data) = > {if (err) {console.log (err); return) } for (let I = 0; I

< data.length; i++) { fs.stat(path + '/' + data[i], (error, stats) =>

{if (stats.isDirectory ()) {dirArr.push (data [I]);})} console.log (dirArr); / / []} console.log (dirArr); / / [] * / print out 3 3 / for (var I = 0; I)

< 3; i++) {// setTimeout(function () {// console.log(i);// }, 100)// }//1、改造for循环 递归实现 var path = './wwwroot';var dirArr = [];fs.readdir(path, (err, data) =>

{if (err) {console.log (err); return;} (function getDir (I) {if (I = = data.length) {/ / complete console.log (dirArr); return;} fs.stat (path +'/'+ data [I], (error, stats) = > {if (stats.isDirectory ()) {dirArr.push (Data [I])) } getDir (I + 1)}) (0)}) / / 2, the new feature async await//1 in nodejs, the method of defining an isDir to determine whether a resource is a directory or a file async function isDir (path) {return new Promise ((resolve,reject) = > {fs.stat (path, (error, stats) = > {if (error) {console.log (error)) Reject (error) return;} if (stats.isDirectory ()) {resolve (true);} else {resolve (false) }})})} / 2. Get all the resources in the wwwroot to cycle through function main () {var path='./wwwroot' var dirArr= []; fs.readdir (path,async (err,data) = > {/ / Note if (err) {console.log (err); return;} for (var iTuno / I {str+=data) Count++;}) readStream.on ('end', () = > {console.log (str); console.log (count)}) readStream.on (' error', (err) = > {console.log (err);})

13. Fs.createWriteStream writes to the file var fs = require ("fs"); var data ='I get the data from the database and I want to save it'; / / create a writable stream and write it to the file output.txt var writerStream = fs.createWriteStream ('output.txt'); / / write data writerStream.write (data,'UTF8') using utf8 encoding; / / mark the end of the file writerStream.end () / / handle stream events-- > finish event writerStream.on ('finish', function () {/ * finish-triggered when all data has been written to the underlying system. * / console.log ("write completed.") ;}); writerStream.on ('error', function (err) {console.log (err.stack);}); console.log ("Program completed"); 14. Pipeline flow

The pipeline provides a mechanism for the output stream to the input stream. We usually use it to get data from one stream and pass it to another.

Var fs = require ("fs"); / / create a readable stream var readerStream = fs.createReadStream ('input.txt'); / / create a writable stream var writerStream = fs.createWriteStream (' output.txt'); / / read and write the contents of the input.txt file / / read and write the contents to the output.txt file readerStream.pipe (writerStream); console.log ("Program execution completed") After reading this, the article "how to use the fs module of Nodejs" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it yourself. If you want to know more about the article, please follow the industry information channel.

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