This is the 17th day of my participation in the August More text Challenge. For details, see:August is more challenging

🎉 preface

  • I remember my first contact with learningnodeWhen still follow rookie tutorial to learn one by one, time has been quite long, usually if not how to use the words will slowly forget some 😅.
  • When learning at that time, I feel a little confused, I do not know why to learn 🤯, some companies rarely need you willnodeNot even. I’m sure there are a lot of beginner players who think the same 🤧. With this in mind, I want to relearnnodeAnd stoodLearners’The point of view ofSharing with empathyTake a look at thisEnough refers to the northSeries, hope to help you 😆.
  • I believe you want to learnnodeAlso in order to be able to write their own data to show, to achieve the increase, delete, check and change, this series in order to take care of the novice students will talk about the basis of comparison, the purpose is to meet the front endnodetheenoughThe target.
  • This article mainly sharesnodetheFile operations, the full text2400 +Words, reading may take ten minutes. specificRefers to the wizardAt the bottom of the article, will continue to update oh, welcome to like the collection ❤️❤️~

👻 NodeJS file operation

  • NodeJSIn addition to being great on the web, it can also operate on files, logically speaking, as long as we use them properlyapiWith some data processing, we can do a lot of things locally.
  • We saw in the last article that if you want to reference a module, you need to userequireAnd the main character I want to introduce today isfsModule, that isNodeJSBuilt-in file module, this module has a lot ofAPIFor our use.

🎈 Create directories and files

  • We can usefs.mkdir fs.writeFileTo create directories and files separately.
  • mkdir()We can take three arguments, the first one is a path, the second one is an optional permission, which we don’t usually need, and the third one is a callback function, which we can do some processing in.
/* learnNode.js */ let fs = require('fs'); Fs. Mkdir (js, (err) = > {the if (err) {the console. The log (' error ')} else {the console. The log (' posture ')}})Copy the code
  • writeFile()You can take four arguments, the first is the path, the second is the contents of the file, the third is an optional permission, and the fourth is a callback function.
/* learnNode.js */ let fs = require('fs'); Fs. WriteFile ('. / js/newJs. Js', 'the console. The log (" into the ")', (err) = > {the if (err) {the console. The log (' error ')} else {the console. The log (' no mistake ')}})Copy the code

  • You can see that we have successfully created the directory and written a file.

🎈 Detecting files

  • We can go throughfs.statTo check whether a file in a path is a directory or a file, and then do something about it.
/* learnNode.js */ let fs = require('fs'); fs.stat('./js/newJs.js', (error, stats) => { if(error) { console.log(error); return false; } else {console.log(' whether file: ${stats.isfile ()} '); Console. log(' whether directory: ${stats.isdirectory ()} '); return false; }})Copy the code
  • Star () takes two arguments. The first is the file to be detected, and the second is a callback function. The callback function takes two argumentserrErrors andstatsObject, this object provides information about the file, we can make judgments on this object information.

🎈 Delete files and directories

  • Since we can useNodeJSCreate files and of course we can delete files, mainly usingfs.unlink``fs.rmdirThe twoAPI.
/* learnNode.js */ let fs = require('fs'); fs.unlink('./js/newJs.js', (err) => { if (err) throw err; Console. log(' file deleted '); }); fs.rmdir('./js',(err)=>{ if (err) throw err; Console. log(' directory deleted '); })Copy the code
  • The twoAPIEach receives two parameters, the path and the callback function, respectively, to executenode learnNode.jsYou can see that our file has been successfully deleted.

🎈 rename

  • We can usefs.renameTo rename the file.
/* learnNode.js */ let fs = require('fs'); Fs. Rename (' oldJs. Js', 'newJs. Js' (err) = > {the if (err) {the console. The log (' error')} else {the console. The log (' posture ')}})Copy the code
  • rename()The first argument is the path, the second is the changed name, and the third is the callback function. It is worth noting that if the first argument and the second argument are in a different location, it will not rename the previous file but cut the file and put it in another place.
/* learnNode.js */ let fs = require('fs'); Fs. Rename (' newJs. Js', '. / js/oldJs. Js', (err) = > {the if (err) {the console. The log (' error ')} else {the console. The log (' shear to the js folder ')}})Copy the code

🎈 Additional content

  • We talked about adding text to the file while creating it. Can we append text to the file directly? We can usefs.appendFile.
/* learnNode.js */ let fs = require('fs'); Fs. AppendFile (' newJs. TXT ', 'I am a supplemental content, (err) = > {the if (err) {the console. The log (' error')} else {the console. The log (' additional content ')}})Copy the code
  • appendFile()You can take three arguments, the first is the path, the second is the content, and the third is the callback function, which executesnode learnNode.jsCan.

🎈 Read files and read directories

  • All above is to add, delete and change the operation of the file, we now also need to master the read content, we can usefs.readFileandfs.readdirRead files and read directories separately.
/* learnNode.js */ let fs = require('fs'); Fs.readfile (' newjs.txt ', (err, data) => {if(err) {console.log(' error '); } else {console.log(" Read file successfully! ") ); console.log(data); }})Copy the code

/* learnNode.js */ let fs = require('fs'); Fs. Readdir ('/', (err, data) = > {the if (err) {the console. The log (' error '); } else {console.log(" Read directory successfully! ") ); console.log(data); }})Copy the code

  • You can see the two of usAPIBoth take two arguments, the first one is the path and the second one is the callback function. This callback function also takes two argumentsdataInformation. We can print thisdataInformation to get the content.

👻 stream (flow)

  • Let’s talk a little bit at the endstreamThe translation isflowWhat do you think of when you think of a flow, a river, a flow, it goes from one source to another, just like a faucet goes from the switch to the ground,streamIt’s also a process.
  • There are four types of Stream:
    • Readable – Readable operations.
    • Writable – Writable operations.
    • Duplex – Readable and writable operations.
    • Transform – The operation is written to data and the result is read.
  • We also have events that we can use during the stream process, such as when an error is detectederror, triggered when data is availabledata.
    • Data – Triggered when data is available to read.
    • End – Triggered when no more data is available to read.
    • Error – emitted when an error occurs during a receive or write.
    • Finish – triggered when all data has been written to the underlying system.
  • Let’s take a quick example to understand.

🎈 read flow

var fs = require("fs");
var data = '';
// 创建可读流
var readerStream = fs.createReadStream('newJs.txt');
// 设置编码为 utf8。
readerStream.setEncoding('UTF8');
// 处理流事件 遇到有数据时执行这个
readerStream.on('data', function(chunk) {
  data += chunk;
  console.log(chunk,'流遇到数据了')
});
// 处理流事件 流结束时执行这个
readerStream.on('end',function(){
  console.log(data,'流结束了');
});
 // 处理流事件 流报错时执行这个
readerStream.on('error', function(err){
  console.log(err.stack);
});
console.log("程序执行完毕");
Copy the code
  • We can start by creating a readable streamfs.createReadStream()The argument is the path of the file you want to read.
  • Executed when data is encounteredreaderStream.on('data',callback()), as shown in the figure below.
  • Executes when the stream endsreaderStream.on('end',callback()), as shown in the figure below.

🎈 stream

  • We have shown how to read a file from a stream. Now let’s try writing to a file from a stream.
var fs = require("fs"); Var data = 'I'm Lou, I'll write in stream '; Var writerStream = fs.createWritestream (' newjs.txt '); Writerstream. write(data,' utf8 '); // Mark the end of the file writerStream.end(); Writerstream. on('finish', function() {console.log(" write done "); }); writerStream.on('error', function(err){ console.log(err.stack); }); Console. log(" Program execution completed ");Copy the code
  • We first create a stream and then we willdataData is written tonewJs.txtFile.
  • Executes when the stream has finished writingreaderStream.on('finish',callback()), as shown in the figure below.

  • You can see that thenewJs.txtThe data we wrote already exists in the file.

👋 at the end

  • On the wholeNodeJSprovidesfsFile manipulation module, this module has manyAPIThe above is just a brief demonstration, there are a lot of interestingAPIYou just need to go to the website when you need it, becauseNodeJSCan operate files, as small as file search, as large as code compilation. On the other hand, most front-end tools can be written with almost nothing more than some data processing logic and some file manipulation.
  • This article is enough to point to the north to end here, in order to take care of the new special basis, please forgive the big guys ha ~~
  • If you think this article is helpful to your words might as well 🍉 attention + thumbs up + favorites + comments + forwarding 🍉 support yo ~~😛

🌅 indicates the north wizard

“From scratch” front-end node can refer to north (1)⚡– installation and module

“Starting from zero” front-end node is sufficient to refer to north (2)⚡– file operations

“From zero” front-end node is sufficient to refer to north (3)⚡– network operations

“From scratch” front-end node is enough to refer to north (4)⚡– Express framework

“From scratch” front-end node can be used to refer to north (5)⚡– connect to the database

“From zero” front-end node can be used to refer to north (6)⚡- actual data large screen