JavaScript does not have the ability to manipulate files, but Node does. Node provides the file system module, which is very important and frequently used in Node. It is definitely a module system to master.
Fs module provides a lot of interfaces, here is mainly to say some commonly used interfaces.
1. Quick review of common apis
fs.stat
Check whether it 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(` file:${stats.isFile()}`)
console.log(` directory:${stats.isDirectory()}`)}})Copy the code
fs.mkdir
Create a directory
const fs = require('fs')
fs.mkdir('logs'.error= > {
if(error) {
console.log(error)
} else {
console.log('Directory created successfully! ')}})Copy the code
fs.rmdir
Delete the directory
const fs = require('fs')
fs.rmdir('logs'.error= > {
if(error) {
console.log(error)
} else {
console.log('Directory logs were deleted successfully')}})Copy the code
fs.writeFile
Create write file
const fs = require('fs')
fs.writeFile('logs/hello.log'.'hello ~ \ n'.error= > {
if(error) {
console.log(error)
} else {
console.log('Write file successfully'); }})Copy the code
fs.appendFile
Additional documents
const fs = require('fs')
fs.appendFile('logs/hello.log'.'hello~\n'.error= > {
if(error) {
console.log(error)
} else {
console.log('Write file successfully'); }})Copy the code
fs.readFile
Read the file
const fs = require('fs')
fs.readFile('logs/hello.log'.'utf-8'.(error, data) = > {
if(error) {
console.log(error)
} else {
console.log(data); }})Copy the code
fs.unlink
Delete the file
const fs = require('fs')
fs.unlink(`logs/${file}`.error= > {
if(error) {
console.log(error)
} else {
console.log('Successfully deleted file:${file}`)}})Copy the code
fs.readdir
Read the directory
const fs = require('fs')
fs.readdir('logs'.(error, files) = > {
if(error) {
console.log(error)
} else {
console.log(files); }})Copy the code
fs.rename
Rename, 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 successful')}})Copy the code
2. Use of the third-party NPM package mkdirp
You can run the mkdirp command to create not only folders but also multilayer folders
midir -p tmp/foo/bar/baz
Copy the code
The above command can also create multiple folders in the current directory.
The following code generates multi-level folders in the current directory
const mkdirp = require('mkdirp')
mkdirp('tmp/foo/bar/baz').then(made= > console.log('create directory at:${made}`))
/ / create the directory: / Users/zhangbing/lot/CodeTest/Node/fs/TMP
Copy the code
The results of
3. Practical examples
Practice 1
Check whether there is an Upload directory on the server. If not, create the directory; if not, do nothing
const fs = require('fs')
const path = './upload'
fs.stat(path, (err, data) = > {
if(err) {
// Create a directory
mkdir(path)
return
}
if(data.isDirectory()) {
console.log('Upload directory exists');
}else{
// Delete the file before creating the directory
fs.unlink(path, err= > {
if(! err) { mkdir(path) } }) } })function mkdir(dir) {
fs.mkdir(dir, err= > {
if(err) {
console.log(err);
return}})}Copy the code
Actual combat 2
Under the wwwroot folder are images CSS JS and index.html. Find all the directories under the wwwroot directory and place them in an array
Use the synchronous method approach
const fs = require('fs')
const path = './wwwroot'
const dirArr = []
const dirs = fs.readdirSync(path)
dirs.forEach(item= > {
if(fs.statSync(path + '/' + item).isDirectory()) {
dirArr.push(item)
}
})
console.log('dirArr', dirArr)
// dirArr [ 'css', 'images', 'js' ]
Copy the code
Use async/await mode
const fs = require('fs')
const path = './wwwroot'
const dirArr = []
function isDir(path) {
return new Promise((resolve, reject) = > {
fs.stat(path, (error, stats) = > {
if(error) {
console.log(error)
reject(error)
return
}
if(stats.isDirectory()) {
resolve(true)}else {
resolve(false)}})})}function main(){
fs.readdir(path, async (error, data) => {
if(error) {
console.log(error)
return
} else {
for(let i = 0; i < data.length; i++) {
if(await isDir(path + '/' + data[i])) {
dirArr.push(data[i])
}
}
console.log('dirArr', dirArr)
}
})
}
main() // dirArr [ 'css', 'images', 'js' ]
Copy the code
4. The pipe flow
Pipes provide a mechanism for an output stream to an input stream. Typically 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 a readable stream
const readerStream = fs.createReadStream('input.txt')
// Create a writable stream
const writerStream = fs.createWriteStream('output.txt')
// Pipe read and write operations
// Read the contents of input. TXT and write the contents to output. TXT
readerStream.pipe(writerStream)
console.log("Program completed")
Copy the code
fs.createReadStream
Reads data from a file stream
const fs = require('fs')
const fileReadStream = fs.fileReadStream('demo1.js')
let count = 0
let str = ' '
fileReadStream.on('data'.chunk= > {
console.log(`${++count}To receive:${chunk.length}`)
str += chunk
})
fileReadStream.on('end'.() = > {
console.log('end -- -- -- -- -- --)
console.log(count + ', ' + star)
})
fileReadStream.on('error'.error= > {
console.log(error)
})
Copy the code
fs.createWriteStream
Written to the file
const fs = require("fs")
const data ='I'm getting the data from the database, I'm going to save it.'
// Create a stream that can be written to the file output.txt
const writerStream = fs.createWriteStream('output.txt')
// Write data using UTF8 encoding
writerStream.write(data,'UTF8')
// Mark the end of the file
writerStream.end()
// Process the stream event --> 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 completed")
Copy the code
Practice: Copy pictures
There is an image 2020.png in the project root directory. Copy it to /wwwroot/images
The following code
const fs = require("fs")
const readStream = fs.createReadStream('./2020.png')
const writeStream = fs.createWriteStream('./wwwroot/images/2021.png')
readStream.pipe(writeStream)
Copy the code
Fs.createwritestream (‘./wwwroot/images/’) : fs.createWritestream (‘./wwwroot/images/’) : fs.createWritestream (‘./wwwroot/images/’) : fs.createWritestream (‘./wwwroot/images/’)
Error: EISDIR: illegal operation on a directory, open <directory>
Copy the code
Source: github.com/dunizb/Code…
Pay attention to this bald, stall, selling, and constantly learning programmer, read the latest articles first, and publish new articles two days first. Attention can receive the gift package, you can save a lot of money!