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

