Scenario Requirement 1: Check whether an Upload directory exists on the server. If no, create the directory. If yes, do not perform operations
Implementation method 1:
Step 1: Encapsulate a function that creates a directory based on the parameters passed in to the directory path
const fs=require('fs'); function mkdir(dir){ fs.mkdir(dir,(err)=>{ if(err){ console.log(err); return; }})}Copy the code
First use fs.stat to determine whether there is an upload directory. If there is an upload but the upload is not a directory, delete the upload file first and then create the upload directory
Var path='./upload' fs.stat('./upload',(err,data)=>{if(err){// create directory mkdir(path) return; } if(! Data.isdirectory ()){console.log('upload not a directory ') fs.unlink(path,(err)=>{if(! err){ mkdir(path); }else{console.log(' Please check incoming data for correctness ')}})}})Copy the code
Implementation method two:
Var mkdirp =require('mkdirp'); Directories must be directories directories ('./upload'). Then (made => console.log(' made directories, starting with ${made} '))Copy the code
Scenario requirement 2: Under the wwwroot file there are img CSS js and index.html. Find all the directories under the wwwroot directory and place them in an array
The build directory structure is: the yellow box is the entry file code
One way to fail is to write it incorrectly: not taking into account the impact asynchrony will have on your code
Scene into:
for(var i=0; i<3; i++){ setTimeout(function(){ console.log('i', i) },100) } // i 3 i 3 i 3Copy the code
Function getData(){// Ajax setTimeout(function(){var name=' z3 '},1000) return name; } // // Obtain data console.log(getData()) //name is not definedCopy the code
Function getData(callback){//ajax setTimeout(function(){var name=' callback '; GetData (function(name){console.log(name)})Copy the code
The basic idea of failure method 1: Declare an empty array (dirArr) and a destination path (‘./wwwroot’). Use fs.readdir to read the destination directory. You want to use fs.stat to place data judged to be a directory in the array dirArr.
Var dirArr=[]; var path='./wwwroot' fs.readdir(path,(err,data)=>{ if(err){ console.log(err); return; } console.log('data',data) // the second is executed -- data does have for(var I =0; i<data.length; i++){ fs.stat(path+'/'+data[i],(error,stats)=>{ if(stats.isDirectory()){ dirArr.push(data[i]) } }) } Console. log('dirArr111', dirArr)}) console.log('dirArr222', dirArr) // the first is executed -- because fs.readdir is asynchronousCopy the code
Fs. stat is an asynchronous method in the for loop. The data in the for loop does not match the expected resultCopy the code
The transformation of the successful method two basic ideas using IIFE and recursive implementation
var dirArr=[];
var path='./wwwroot'
fs.readdir(path,(err,data)=>{
if(err){
console.log(err);
return;
}
(function getDir(i){
if(i==data.length){
console.log('dirArr', dirArr)
return;
}
fs.stat(path+'/'+data[i],(error,stats)=>{
if(stats.isDirectory()){
dirArr.push(data[i])
}
getDir(i+1)
})
})(0)
})
Copy the code
The basic idea of the third advanced method: async and await. Define an isDir method to determine whether a resource is a directory or a file. This method returns true if it is a directory and false if it is not
async function isDir(path){
return new Promise((resolve,reject)=>{
fs.stat(path,(error,stats)=>{
if(error){
console.log(error)
reject(error)
}
if(stats.isDirectory()){
resolve(true)
}else{
resolve(false)
}
})
})
}
Copy the code
function main(){ var path='./wwwroot' var dirArr=[]; Fs. readdir(path, async (err,data)=>{//-- await use in async methods if(err){console.log(err); return; } for(var i=0; i<data.length; i++){ if(await isDir(path+'/'+data[i])){ dirArr.push(data[i]) } } console.log(dirArr) }) } main();Copy the code
Async and await
/** * async is short for 'async' and await can be considered short for async. So it is easy to understand that async is used to declare an asynchronous function, and await is used to wait for an asynchronous method to completeCopy the code
Function test(){return 'hello node.js'} console.log(test()) // hello node.js async function test(){return' hello node.js'} Console.log (test()) //Promise {' Hello node.js'}Copy the code
Wrong way to write:
3. Incorrect spelling: Async function test(){return 'hello node.js'} console.log(await test()) // error -await must be used in async methods -await must be used in async methods "Await" is used in async methodsCopy the code
Correct way to write it:
Async function test(){return 'hello node.js'} async function main(){var data=await test(); Console. log(data)} main(); Hello/node. JsCopy the code
Encapsulate an asynchronous method with async and return a promise
Async function test() {return new Promise((res,rej)=>{setTimeout(()=>{var name=' async data '; Res (name)},100)})} // async function main(){var data=await test(); Console. log(data) // Asynchronous data} main();Copy the code
- The structure of the build directory is:
readFileSync
Read the file
// require("fs") const fs = require("fs"); // let res = fs.readFileSync("1.txt"); // console.log(res.toString());Copy the code
fs.createReadStream
Reads data from a file stream
var fs=require('fs') var readStream=fs.createReadStream('./input.txt') var count=0; var str=''; Readstream. on('data',(data)=>{STR +=data; count++; }) readStream.on('end',()=>{ console.log(str,count) }) readStream.on('error',(err)=>{ console.log(err) })Copy the code
Fs.createwritestream Writes data from the file stream
Var fs = the require (" fs "); Var data= 'I got the data from the database, I want to save it '; var str=''; for(var i=0; i<500; /n'} var writeStream= fs.createWritestream ('./ oupue.txt ') writestream.write (STR); Finish writestream.end (); WriteStream. On (' finish ', () = > {the console. The log (' write complete ')})Copy the code
Create readable streams while creating writable streams for normal read and write operations
// Create a writable stream var readStream= fs.createreadStream ('./input.txt' WriteStream = fs.createWritestream ('./ouput.txt') // Common read and write operations // Read the contents of input. TXT and copy the contents to ouput.txt Readstream.pipe (writeStream) console.log(' Executed successfully ')Copy the code
- Case 1: Create a 65KB file readable stream while creating a 65KB file writable stream and import a 65KB file
const fs = require("fs"); // create a readable stream let rs = fs.createreadStream (" 65KB "); Let ws = fs.createWritestream ("2.txt"); let ws = fs.createWritestream ("2.txt"); Rs.pipe (ws); let num = 0; let str = ""; rs.on("data",chunk=>{ num++; str += chunk; // console.log(chunk); console.log(num); }) // The stream reads the completed event; rs.on("end",()=>{ console.log(str); }) // The stream transfers the data into 64KB small files (64KB groups); // create a 65KB file let buffer = buffer. alloc(65*1024); fs.writeFile("64kb",buffer,err=>{ if(err){ return console.log(err); } console.log(" Write successfully "); })Copy the code