NodeJs learning - basic (b) -fs

In the background operation, the operation will certainly file stream, nodeJs file operations --- FS

A: introduction

let fs = require('fs')

Second, read the contents of the file --- readFile

1, create a file: a.text file contents: bbb

2 reads

fs.readFile('./a.text',(err,data)=> {
    if (err) {
        throw err
        console.log(err)
    } else {
        console.log(data.toString())
    }
})

3, content presentation

 

 

Third, write to the file contents --- writeFile

1, write to

/ **
* write
* the file path
* written content
* whether to overwrite (if not write it overwrites the original content)
* callback
* * /

fs.writeFile('./b.text','bbb',{flag: 'a'}, (err) => {
    if (err) {
        throw err
    } else {
        console.log('写入成功')
    }
})

Note: If it does not, the system will default to you to create this file

 2, view results

 

 Fourth, the synchronous read --- readFileSync (file path)

let data = fs.readFileSync('./b.text')

Fifth, the synchronous write --- writeFileSync (file path, write content, flag)

let data = fs.writeFileSync('./b.text','cccc',{flag: 'a'})

 

Guess you like

Origin www.cnblogs.com/WQLong/p/12600691.html