Principle and Common Uses of Node. js fs Module
- 2021-09-04 23:14:09
- OfStack
JavaScript has no ability to operate files, but Node can do it. Node provides a module to operate file system, which is a very important and high-frequency module used in Node, and is a module system that must be mastered absolutely.
fs module provides a lot of interfaces, and here we mainly talk about some commonly used interfaces.
1. Quick review of commonly used API
fs. stat Detection is a file or a directory
const fs = require('fs')
fs.stat('hello.js', (error,stats)=>{
if(error) {
console.log(error)
} else {
console.log(stats)
console.log(` Documents: ${stats.isFile()}`)
console.log(` Directory: ${stats.isDirectory()}`)
}
})
fs. mkdir Create Directory
const fs = require('fs')
fs.mkdir('logs', error => {
if(error) {
console.log(error)
} else {
console.log(' Directory created successfully! ')
}
})
fs. rmdir delete directory
const fs = require('fs')
fs.rmdir('logs', error => {
if(error) {
console.log(error)
} else {
console.log(' The directory was successfully deleted logs')
}
})
fs. writeFile Create Write File
const fs = require('fs')
fs.writeFile('logs/hello.log',' How do you do ~\n', error => {
if(error) {
console.log(error)
} else {
console.log(' Write to file successfully ');
}
})
fs. appendFile append file
const fs = require('fs')
fs.appendFile('logs/hello.log','hello~\n', error => {
if(error) {
console.log(error)
} else {
console.log(' Write to file successfully ');
}
})
fs. readFile Read File
const fs = require('fs')
fs.readFile('logs/hello.log','utf-8', (error, data) => {
if(error) {
console.log(error)
} else {
console.log(data);
}
})
fs. unlink delete file
const fs = require('fs')
fs.unlink(`logs/${file}`, error => {
if(error) {
console.log(error)
} else {
console.log(` File deleted successfully: ${file}`)
}
})
fs. readdir Read Directory
const fs = require('fs')
fs.readdir('logs', (error, files) => {
if(error) {
console.log(error)
} else {
console.log(files);
}
})
fs. rename rename, and you can also change the file storage path
const fs = require('fs')
fs.rename('js/hello.log', 'js/greeting.log', error => {
if(error) {
console.log(error)
} else {
console.log(' Rename succeeded ')
}
})
2. Use of the third party npm package mkdirp
mkdirp can not only create folders, but also create multiple layers of folders, similar to the mkdir-p command
midir -p tmp/foo/bar/baz
The above command can also create multiple layers of folders in the current directory.
The following code generates a multilevel folder in the current directory
const mkdirp = require('mkdirp')
mkdirp('tmp/foo/bar/baz').then(made = > console. log (` Create directory at: ${made} `))
//Create directory at:/Users/zhangbing/github/CodeTest/Node/fs/tmp
3. Practical examples
Actual Combat 1
Determine if there is an upload directory on the server. If not, create this directory, and if so, do not do anything
const fs = require('fs')
const path = './upload'
fs.stat(path, (err, data) => {
if(err) {
// Performing the creation of a directory
mkdir(path)
return
}
if(data.isDirectory()) {
console.log('upload Directory exists ');
}else{
// Delete the file first, and then perform the creation of the directory
fs.unlink(path, err => {
if(!err) {
mkdir(path)
}
})
}
})
function mkdir(dir) {
fs.mkdir(dir, err => {
if(err) {
console.log(err);
return
}
})
}
Actual Combat 2
There are images css js and index. html under the wwwroot folder. Find all the directories under the wwwroot directory and put them in an array
Using synchronous methods
const fs = require('fs')
fs.mkdir('logs', error => {
if(error) {
console.log(error)
} else {
console.log(' Directory created successfully! ')
}
})
0
Use async/await mode
const fs = require('fs')
fs.mkdir('logs', error => {
if(error) {
console.log(error)
} else {
console.log(' Directory created successfully! ')
}
})
1
4. Pipeline flow
Pipeline provides a mechanism from output stream to input stream. Usually, we use it to get data from one stream and pass it to another stream. In the following example, we read the contents of one file and write the contents to another file.
const fs = require("fs")
//Create 1 readable stream
const readerStream = fs.createReadStream('input.txt')
//Create 1 writable stream
const writerStream = fs.createWriteStream('output.txt')
//Pipeline read and write operations
//Read the contents of the input. txt file and write the contents to the output. txt file
readerStream.pipe(writerStream)
console. log ("Program finished")
fs. createReadStream Reading data from a file stream
const fs = require('fs')
fs.mkdir('logs', error => {
if(error) {
console.log(error)
} else {
console.log(' Directory created successfully! ')
}
})
2
fs. createWriteStream write to file
const fs = require("fs")
const data = 'I got the data from the database, I want to save it'
//Create a writable stream to the file output. txt
const writerStream = fs.createWriteStream('output.txt')
//Write data using utf8 encoding
writerStream.write(data,'UTF8')
//Mark end of file
writerStream.end()
//Handle flow events-- > finish event
writerStream.on('finish', () = > {
/*finish-Triggered when all data has been written to the underlying system. */
console. log ("Write complete. ")
})
writerStream.on('error', err = > {
console.log(err.stack);
})
console. log ("Program finished")
Actual combat: copying pictures
There is a picture 2020. png in the project root directory, copy it to/wwwroot/images
The code is as follows
const fs = require("fs")
const readStream = fs.createReadStream('./2020.png')
const writeStream = fs.createWriteStream('./wwwroot/images/2021.png')readStream.pipe(writeStream)
It is important to note that the directory 1 to be written to fs. createWriteStream must carry the file name to be copied, that is, it cannot be written as fs. createWriteStream ('./wwwroot/images/') otherwise the following error will be reported under macOS:
Error: EISDIR: illegal operation on a directory, open < directory >