node. js in FS module
Common features
Implementing read- Write directory operations for files
-Synchronous and asynchronous coexistence, asynchronous without synchronization
-Fs.readfile cannot read a file that is larger than the running memory and will not use the ReadFile method if the file is too large
-File large shunt read, stream
- introduction of FS module
-Let Fs=require (' FS ')
Read files synchronously
-fs.readfilesync(' path ', UTF8);
Let Result=fs.readfilesync ('./1.txt ', ' UTF8 ');
Asynchronously reads the file, catches the error with the parameter err
-FS. ReadFile (' path ', ' UTF8 ', function () {})
Fs.readfile ('./name.txt ', ' UTF8 ', function (err,data) {
if (err) {
Console.log (ERR)
}else{
Console.log (data)
}
})
Write files synchronously
- Fs.writefilesync("path", data written)
Fs.writefilesync ("./1.txt", Json.stringify ({name:1}))
Writing Files Asynchronously
- fs.writefile(' path ', data written, callback)
Fs.writefile ('./1.txt ', ' aaaaa ', function (err) {
if (err) {
Console.log (ERR);
}
})
Write a copy instance of a read-write file
Let Fs=require ("FS"); // Synchronous Copy function Copysync (source,target) {// synchronous Read let Result=fs.readfilesync (source, ' UTF8 '); // Synchronous Write Fs.writefilesync (Target,result);} Copysync ("./age.txt", './1.txt ');
Asynchronous copy
function Copy (sourse,target,callback) {
Asynchronous read
Fs.readfile (sourse, ' UTF8 ',function(err,data) {if(err) {return Callback (ERR)}else{// asynchronously writes fs.writefile (Target,data,callback)}});}; Copy ('./name.txt ', './ss.txt ',function(err) {ifreturn Console.log (err); Console.log (' copy succeeded ')})
determine if the file does not exist
- fs.existssync(' path to file ')
Stat method
Fs.stat (' File path ', function (Err,stat) {
Stat.isdirectory See if it's a folder
Stat.isfile See if it's a file
})
Delete a folder
-Fs.rmdir (' folder path ', function () {})
deleting files
-Fs.unlink (' File path ', function () {})
Determine if the file does not exist
if (Fs.existssync ('./b ' './b ', function (Err,stat) { Span style= "color: #008000;" >// stat is used for server caching // stat.isdirectory look is not the folder Stat.isfile see is not the file if (Stat.isdirectory ()) { // Delete folder Fs.rmdir ('./b ', function () {})} else { delete file fs.unlink ('./b ', function () {});}})}
Use recursion to write a folder and create it sequentially
functionMD (URL) {Let Paths=url.split ('/');//split the a/b/c into arrays [' A ', ' B ', ' C ']Let Index=0; functionMake (path) {if(index===paths.length+1) {//If you go to the end, stop recursion. return false; } if(!fs.existssync (path)) {//does not exist //Create a folderFs.mkdir (Path,function() {Make (Paths.slice (0,++index). Join ('/')) }) }Else{//existMake (Paths.slice (0,++index). Join ('/') }}} make (Paths[index++])//Take the first one out first.}MD (' A/B/C/D ');
node. JS's fs Core module read-write file operation-----Easy-to-digest