Three common methods fs module
1.fs.readFile () - read document
2.fs.writeFile () - write file
3.fa.stat () - view the file information
where fs is different from other modules in the module is that it has both asynchronous and synchronous method, asynchronous method only other modules, the asynchronous and synchronous method name except that after the synchronization method of asynchronous method name plus " Sync "
1.fs.readFile()
// use the ES strict mode
"use strict";
// imports fs module
const fs = require("fs");
fs.readFile("test.txt", "utf-8", function (err, data) {
// whether the file read correctly, err stores error messages when reading
if(err){
console.log(err);
} else {
// print read out when reading the correct information
console.log(data);
}
});
Note: do not add the second parameter "utf-8" when the output data will be a target Buffer
Buffer can be converted into a String: data.toString ()
String Buffer converted into objects: Buffer.from (data, "uft-8");
test.txt with the js script is in the same folder
The above embodiment is an asynchronous read the file, read the file synchronization is the following manner
// determine whether synchronous read error
try{
let file = fs.readFileSync("test.txt", "utf-8");
console.log(file);
} catch( err ) {
// If an error occurs on the print out an error message
console.log(err);
}
2.fs.writeFile()
"use strict";
const fs = require("fs");
fs.writeFile ( "test.txt", "information that you want to write", function (err) {
if(err) {
console.log(err);
} else {
console.log("Write OK!");
}
});
Synchronous write to a file and readFile method is similar to not go into here
3.fs.stat ()
"use strick";
const fs = require("fs");
fs.stat("test.txt", function(err, stat){
if(err) {
console.log(err);
} else {
console.log ( "whether the document:" + stat.isFile ());
console.log ( "whether the folder:" + stat.isDirectory ());
IF (stat.isFile ()) {
// output file size
console.log ( "the size of the file is:" + stat.size);
Creation Date // output file
console.log ( "file creation date is:" + stat.birthtime);
// output last modified date of the file
console.log ( "last modified file date is:" + stat.mtime);
}
}
});
ReadFile synchronization method and a synchronization method similar to, omitted
But stat synchronization method with an asynchronous approach has several different places
Time 1.stat asynchronous method using a time in your area now
2.stat time synchronization method is used when the time zone