[quick review] use of fs module in Node.js


JavaScript does not have the ability to operate files, but node can do it. Node provides the operating file system module, which is a very important and high-frequency module used in node and an absolutely necessary module system.

fs module provides a lot of interfaces. Here we mainly talk about some commonly used interfaces.

1. Quick review of common API

fs.stat detects 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(`Document:${stats.isFile()}`)
        console.log(`Catalog:${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('Directory deleted successfully logs')
    }
})

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('File written 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('File written 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(`Successfully deleted file: ${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. You can also change the storage path of the file

const fs = require('fs')
fs.rename('js/hello.log', 'js/greeting.log', error => {
    if(error) {
        console.log(error)
    } else {
        console.log('Rename successful')
    }
})

2. Use of the third party NPM package mkdirp

mkdirp You can not only create folders, but also create multi-layer folders, similar to the mkdir-p command

midir -p tmp/foo/bar/baz

The above command can also create multiple folders in the current directory.

The following code generates a multi-level folder in the current directory

const mkdirp = require('mkdirp')

mkdirp('tmp/foo/bar/baz').then(made => console.log(`Create directory at: ${made}`))

// Create directory in / Users/zhangbing/github/CodeTest/Node/fs/tmp

Result

3. Practical examples

Actual combat 1

Determine whether there is an upload directory on the server. If not, create this directory. If there is one, do not operate

const fs = require('fs')

const path = './upload'
fs.stat(path, (err, data) => {
    if(err) {
        // Execute create directory
        mkdir(path)
        return
    }
    if(data.isDirectory()) {
        console.log('upload Directory exists');
    }else{
        // Delete the file first, and then create 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

Under the wwwroot folder are images css js and index.html. Find all the directories under the wwwroot directory and put them in an array

Use synchronization method

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' ]

Using 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' ]

4. pipe flow

The pipeline provides a mechanism for output flow to input flow. Usually we are used to get data from one flow and pass it to another. In the following example, we read the contents of one file and write them 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')
//Pipeline read / write operation
//Read the contents of the input.txt file and write the contents to the output.txt file
readerStream.pipe(writerStream)
console.log("Program execution completed")

fs.createReadStream read data from file stream

const fs = require('fs')
const fileReadStream = fs.fileReadStream('demo1.js')
let count = 0
let str = ''
fileReadStream.on('data', chunk => {
    console.log(`${++count}Received:${chunk.length}`)
    str += chunk
})
fileReadStream.on('end', () => {
    console.log('---End---')
    console.log(count + ',' + star)
})
fileReadStream.on('error', error => {
    console.log(error)
})

fs.createWriteStream write file

const fs = require("fs")
const data ='I got the data from the database. I want to save it'
//Create a writable stream and write it 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()
//Process flow 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 execution completed")

Practice: copying pictures

There is a picture 2020.png in the root directory of the project, 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 should be noted that the directory to be written by fs.createWriteStream must have 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 Mac OS:

Error: EISDIR: illegal operation on a directory, open <directory>

Source code: https://github.com/dunizb/CodeTest/tree/master/Node/fs

Published 33 original articles, won praise 4, visited 1329
Private letter follow

Keywords: github Javascript npm Database

Added by Davo on Thu, 05 Mar 2020 10:58:03 +0200