liveBook · Manning

Filesystem API

As explained in The Joy of JavaScript

An interface exposed by a runtime or operating system for reading, writing, and managing files and directories.

A filesystem API exposes runtime operations for accessing files. In Node.js, the fs library offers synchronous, callback-based, and Promise-based forms; the asynchronous forms avoid blocking the main thread. section 8.2

Choose an access style according to how the surrounding application handles latency:

  • Synchronous access, such as fs.readFileSync, pauses the main thread and suits only simple one-off scripts. section 8.2
  • Callback access, such as fs.readFile, lets the scheduler continue and invokes a callback when file data is ready. section 8.2
  • Promise access, such as fs.promises.readFile, represents filesystem latency as a chainable asynchronous result. section 8.2
  • util.promisify adapts error-first callback APIs when a native Promise form is unavailable. section 8.2

Count blocks through a Promise pipeline

A composable workflow can check access, read the file, decode its contents, tokenize semicolon-delimited data, count the result, and convert failures into a useful error. section 8.2.4

Listing 8.12 Counting all blocks in a file
function countBlocksInFile(file) {
   return fsp.access(file, fs.constants.F_OK | fs.constants.R_OK)
      .then(() => {                                                 #1
         return fsp.readFile(file)
      })
      .then(decode('utf-8'))
      .then(tokenize(';'))
      .then(count)
      .catch(error => {
          throw new Error(`File ${file} does not exist or you have 
             no read permissions. Details: ${error.message}`)
       });
}
 
countBlocksInFile('blocks.txt')
   .then(result => {      
      result // 3
   });

Inspect a complete Promise chain that combines access checks, reading, text processing, counting, and error handling. section 8.2.4

How The Joy of JavaScript covers it

How deep it goes
Compares synchronous, callback, promisified, and native Promise forms, then demonstrates a chained file-processing workflow.
Examples
Uses readFileSync, readFile, fs.promises.readFile, util.promisify, and a countBlocksInFile processing pipeline.
What it assumes
Assumes JavaScript asynchronous programming and callbacks while reinforcing promises as abstractions over latency.
What you can do after
Apply it via Node.js fs APIs to read files without blocking and compose subsequent processing with promises.
How it connects
Connects filesystem APIs with promises, callbacks, asynchronous I/O, the event loop, and error-first APIs.

Also explained in

Compare how 2 books explain filesystem API →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.