NodeJS built-in module 1: file and folder operations

fs-(file system) file system

1. Introduction
  • For any server-side language, there will be its own corresponding file system, because the server needs to store various data and files in different places.
  • The file system in Node is fs, which can help us directly operate files on any operating system (macos windows linux), etc., because node is cross-platform
  • Noded fs Api query website
2. Three ways to call API
  • For synchronous operation files (with sync) suffix, the code will be blocked and will not continue to execute.
  • The asynchronous callback function (without sync suffix) calls the function to receive the returned result. When the result is obtained, the callback function is called.
  • Asynchronous Promise operates files, and the code will not be blocked. When called through fs.promise, a promise will be returned, which can be processed through .then and catch.
3. fs file reading
//Introduce fs module
const fs = require('node:fs')
//1. Synchronous reading--the first parameter is the file path, and the second parameter is the encoding format.
//If the encoding format is not passed, the buffer will be returned and needs to be converted.
const res = fs.readFileSync('./abc.text', {<!-- --> encoding: 'utf-8' })
console.log(res);
//2. Asynchronous reading, callback function-there will be callback hell.
fs.readFile('./abc.text', {<!-- --> encoding: 'utf-8' }, (error, data) => {<!-- -->
  if (error) {<!-- -->
    console.log('Error reading file');
  }
  console.log(`The content read from the file is:`, data)
})
//3. Promise calls asynchronously
fs.promises.readFile('./abc.text', {<!-- --> encoding: 'utf-8' }).then(res => {<!-- -->
  console.log('result read by promise', res)
}).catch(e => {<!-- -->
  console.log(`An error occurred`, e.message)
})

Run results

image.png

File descriptor
  • What is a file descriptor?
  1. On common operating systems, for each process, the kernel maintains a table of currently open files and resources.
  2. Each open file is assigned a simple numeric identifier called a file descriptor.
  3. At the system level, all file system operations use these file descriptors to identify and track each specific file.
  4. Windows systems use a different but conceptually similar mechanism to track resources.
  5. To make life easier for users, Node.js abstracts away the specific differences between operating systems and assigns all open files a numeric file descriptor
  • Thefs.open() method is used to allocate a new file descriptor.
  • Once allocated, the file descriptor can be used to read data from the file, write data to the file, or request information about the file.
  • Difference: Get the file descriptor to read the file information, not just read or write
//Call fs.open--the same has asynchronous and synchronous
fs.open('./abc.text', (error, fd) => {<!-- -->
  if (error) return
  //Return file descriptor --number type
  console.log('The file descriptor is:', fd)

  //Files can be read and written through file descriptors
  console.log(fs.readFileSync(fd))
  //Get file information
  fs.fstat(fd, (error, stats) => {<!-- -->
    if (error) return
    console.log(stats)
  })
  //Manual shutdown--otherwise the node process will automatically shut down when it is closed.
  fs.close(fd)
})

Run results

image.png

4. Writing files
//Introduce fs module
const fs = require('node:fs')
//Define what to write
let content = 'Hello, welcome to read my notes, I am Xiao Ajun\\
'
//Write to file--the file will be automatically created if it exists
fs.writeFile('./bbb.txt', content, {<!-- --> encoding: 'utf-8', flag: 'a + ' }, (error) => { <!-- -->
  if (error) return;
  console.log('File written successfully')
})
//The third parameter options{encoding--encoding format, flag---operation mode, a--means append}
  • Flag options are commonflag URL
    1. w opens the file for writing, default value;
    2. w + opens the file for reading and writing (readable and writable), and creates the file if it does not exist;
    3. r opens the file for reading, the default value when reading;
    4. r + opens the file for reading and writing, and throws an exception if it does not exist;
    5. a opens the file for writing and places the stream at the end of the file. Create the file if it does not exist;
    6. a + opens the file for reading and writing, placing the stream at the end of the file. Create file if it does not exist
  • encoding options
    1. For details, please refer to an article by coderWhy for a detailed explanation of character encoding-Jianshu
5. Folder operations
  • Folder creation
//Introduce fs module
const fs = require('node:fs')

//Create folder---asynchronous call
//If it exists, it will fail
fs.mkdir('./I am the folder created by node', (err) => {<!-- -->
  if (err) {<!-- -->
    console.log('Folder creation failed', err)
  } else {<!-- -->
    console.log('Folder created successfully')
  }
})
  • Folder reading
  • This is my folder directory

image.png

//Folder reading---Read the file string in the current folder, first level
fs.readdir('./I am the folder created by node', (err, files) => {<!-- -->
  if (err) return
  console.log(files)//[ '111', '222', 'index.txt' ]
})
//The second method, read the folder type and information--return an array object
fs.readdir('./I am the folder created by node', {<!-- --> withFileTypes: true }, (err, files) => {<!-- -->
  files.forEach(item => {<!-- -->
    if (item.isDirectory()) {<!-- -->
      console.log('item is a folder', item.name)
    } else {<!-- -->
      console.log('item is a file', item.name)
    }
  })
})
  • ** operation result**

image.png

  • Expand recursive call to obtain all files under the folder
//Extension--Recursively obtain all files in the folder
function readDirectory (path) {<!-- -->
  fs.readdir(path, {<!-- --> withFileTypes: true }, (err, files) => {<!-- -->
    if (err) return;
    //Traverse the obtained file array
    files.forEach(file => {<!-- -->
    //Determine whether it is a folder
      if (file.isDirectory()) {<!-- -->
      //continue recursion
        readDirectory(`${<!-- -->path}/${<!-- -->file.name}`)
      } else {<!-- -->
        console.log('My file name is', file.name)
      }
    })
  })
}
readDirectory('./I am the folder created by node')
  • Run results

image.png

6. Renaming files and folders
//Folder rename
fs.rename('./I am a folder created by node', './I want to change the name', (err) => {
  if (err) {
    console.log('Renaming failed')
  }
})
//File rename
fs.rename('./I want to change my name/index.txt', './I want to change my name/666.txt', (err) => {
  if (err) {
    console.log('Renaming failed')
  }
})