fs module
Commonly used functions
Implementing the fileRead and write directory operations
- Synchronous and asynchronous coexistence, no synchronous if there is asynchronous
- No files with larger memory than running, and if the file is too large, you won't use the readFile method
- Large file diversion reading, stream
- Introducing the fs module
- let fs=require('fs')
Read files synchronously
-('Path',utf8);
let result=('./','utf8');
Read files asynchronously, use parameter err to catch errors
- ('Path','utf8',function(){})
('./','utf8',function(err,data){
if(err){
(err)
}else{
(data)
}
})
Synchronously write files
- ("Path", data written)
("./",({name:1}))
Asynchronously write files
- ('Path', data written, callback)
('./','aaaaa',function (err) {
if(err){
(err);
}
})
Read and write a copy instance of the file
let fs=require("fs"); //Synchronous copyfunction copySync(source,target){ //Synchronous readinglet result=(source,'utf8'); //Synchronous write(target,result); } copySync("./",'./');
//Asynchronous copy
function copy(sourse,target,callback){ //Asynchronous reading(sourse,'utf8',function(err,data){ if(err){ return callback(err) }else{ //Asynchronous write(target,data,callback) } }); }; copy('./','./',function(err){ if(err) return (err); ('Copy successfully') })
Determine whether the file exists or not
- ('Path to file')
stat method
('File Path',function (err,stat) {
See if it is a folder
See if it is a file
})
Delete folder
- ('Folder Path',function(){})
Delete files
- ('File Path',function(){})
//Judge whether the file exists or not
if(('./b')){ ('./b',function (err,stat) { //The time in stat is used for server cache//See if it is a folder? See if it is a file?if(()){ //Delete the folder('./b',function(){}) }else{ //Delete the file('./b',function(){}); } }) }
Use recursion to write a folder to create it in sequence
function md(url) { let paths=('/'); //Split a/b/c into an array ['a','b','c'] let index=0; function make(path){ if(index===+1){ // If you reach the end point, stop recursion return false; } if(!(path)){ //Not exists //Create a folder (path,function () { make((0,++index).join('/')) }) }else{ //exist make((0,++index).join('/')) } } make(paths[index++]) //Take out the first one first} md('a/b/c/d');
The above article is based on the FS core module reading and writing file operation (example explanation) is all the content I share with you. I hope you can give you a reference and I hope you can support me more.