跳到主要内容

Fireship Nodejs Guide

fs

Sync | Blocking

./filesystem-sync-blocking.js
const { readFileSync } = require('fs')

const txt = readFileSync('hello.txt', 'utf8')
console.log(txt)

console.log('do this ASAP')
outcome
❯ node filesystem-sync-blocking.js
Hello from file system

do this ASAP

Async | Non-Blocking

./filesystem-async-non-blocking.js
const { readFile } = require('fs')

readFile('./hello.txt', 'utf8', (err, txt) => {
console.log(txt)
})

console.log('do this ASAP')
outcome
❯ node filesystem-async-non-blocking.js
do this ASAP
Hello from file system

Promise | Non-Blocking

./filesystem-promise-ns.js
const { readFile } = require('fs').promises

async function read() {
const fileContent = await readFile('./hello.txt', 'utf8')
console.log(fileContent)
}

read()
console.log("do this ASAP")
outcome
❯ node filesystem-promise-ns.js
do this ASAP
Hello from fs

Modules

  • COMMON JS: requrie()

  • ES MODULES: import/export

  • npm

    • npm init -y
    • package.json
    • node_modules