I/O file reading and writing

File to read

  1. Read fs.readFileSync synchronously

    const fs = require('fs')
    // Read synchronously
    // Return a Buffer that stores binary information
    // 1 Byte=== 8bit(0/1)
    const data = fs.readFileSync('./conf.js')
    console.log('data', data.toString())
    Copy the code
  2. Read fs.readFile asynchronously

    const fs = require('fs')
    // Read asynchronously
    fs.readFile('./test.js'.(err, data) = > {
      if (err) throw err
      console.log('data', data.toString())
    })
    Copy the code
  3. Async /await read (promisify)

    / / async/await to read
    (async() = > {const fs = require('fs')
      // Util is a library that comes with Node
      // Use promisify to wrap fs.readFile in promise style
      const { promisify } = require('util')
      const readFile = promisify(fs.readFile)
      const data = await readFile('./test.js')
      console.log('data3', data.toString());
    })()
    
    process.nextTick(async() = > {const fs = require('fs')
      const { promisify } = require('util')
      const readFile = promisify(fs.readFile)
      const data = await readFile('./test.js')
      console.log('data4', data.toString())
    })
    Copy the code
  4. File stream steam

    // Copy an image
    // This feature will be used later in the custom CLI tool to implement download dependencies
    const fs = require('fs')
    const rs = fs.createReadStream('./1.jpeg') // Source file stream
    const ws = fs.createWriteStream('./1.copy.jpeg')// The target file stream
    rs.pipe(ws)// Create a conduit copy
    Copy the code