0Pricing
Node.js Backend Development Bootcamp · Pelajaran

Bekerja dengan Sistem Berkas & Aliran

Pelajari cara membaca dan menulis berkas di Node.js menggunakan modul fs, baik secara sinkron maupun asinkron, serta temukan cara aliran memungkinkan Anda memproses data dalam jumlah besar secara efisien.

Bekerja dengan Sistem Berkas & Aliran adalah pelajaran Node.js Backend Development Bootcamp gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Node.js Backend Development Bootcamp, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Node.js Backend Development Bootcamp mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

Why the File System Matters

Most backends eventually read or write files on disk — logs, config, uploads, reports. Node's built-in fs module handles it all; just require it.

const fs = require('fs');
console.log(typeof fs.readFile);

Synchronous vs Asynchronous

Most fs methods come in two flavors: sync (like readFileSync) blocks the event loop, async doesn't. On servers, always prefer async.

const fs = require('fs');
const data = fs.readFileSync('config.txt', 'utf8');
console.log(data);

Reading a File Asynchronously

The classic callback form gives you error first, then data. Always check err before touching the data — a missing file or bad permission lands there.

const fs = require('fs');
fs.readFile('notes.txt', 'utf8', (err, data) => {
  if (err) { console.error('Failed:', err.message); return; }
  console.log('File says:', data);
});

The Promise-Based API

Modern Node exposes a promise-based API under fs/promises — pairs perfectly with async/await and skips callback nesting entirely.

const fs = require('fs/promises');
async function load() {
  const data = await fs.readFile('notes.txt', 'utf8');
  console.log(data);
}
load();

Writing Files

Use writeFile to create or overwrite a file. No file? It's created. File exists? Its contents are replaced wholesale.

const fs = require('fs/promises');
async function save() {
  await fs.writeFile('output.txt', 'Hello from Node!');
  console.log('Saved.');
}
save();

Appending Instead of Overwriting

To add to a file without wiping it, use appendFile — exactly what you want for log files that grow line by line.

const fs = require('fs/promises');
async function log(line) {
  await fs.appendFile('app.log', line + '\n');
}
log('Server started');

Working with Paths

Hard-coded paths break across operating systems. The path module fixes that: path.join uses the right separator, and __dirname is the current file's folder.

const path = require('path');
const full = path.join(__dirname, 'data', 'users.json');
console.log(full);

Checking If a File Exists

Don't check existence first — that risks race conditions. Just try the operation and catch the error; a missing file throws with code ENOENT.

const fs = require('fs/promises');
async function read() {
  try {
    return await fs.readFile('maybe.txt', 'utf8');
  } catch (err) {
    if (err.code === 'ENOENT') return 'default content';
    throw err;
  }
}

Why Streams Exist

Reading a 2 GB file with readFile loads it all into memory — a crash waiting to happen. Streams process data in small chunks, keeping memory low.

const fs = require('fs');
const stream = fs.createReadStream('huge.log', 'utf8');
stream.on('data', chunk => console.log('Got', chunk.length, 'bytes'));

Piping Streams Together

The power move with streams is pipe: connect a readable straight to a writable. Node handles backpressure so a fast reader won't flood a slow writer.

const fs = require('fs');
const read = fs.createReadStream('input.txt');
const write = fs.createWriteStream('copy.txt');
read.pipe(write);

Listing and Creating Directories

The fs module manages folders too: mkdir creates directories (add { recursive: true } for nested paths), and readdir lists contents.

const fs = require('fs/promises');
async function setup() {
  await fs.mkdir('uploads', { recursive: true });
  const files = await fs.readdir('.');
  console.log(files);
}
setup();

Quick Check

Test your understanding of file operations.

Recap

You can now work the file system: fs's sync/callback/promise APIs, async on servers, basic I/O, cross-platform path, and streams for big files.

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Bekerja dengan Sistem Berkas & Aliran” gratis?

Ya — teks lengkap “Bekerja dengan Sistem Berkas & Aliran” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Node.js Backend Development Bootcamp, upgrade ke CoddyKit PRO. Kursus Node.js Backend Development Bootcamp mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Bekerja dengan Sistem Berkas & Aliran”?

Pelajari cara membaca dan menulis berkas di Node.js menggunakan modul fs, baik secara sinkron maupun asinkron, serta temukan cara aliran memungkinkan Anda memproses data dalam jumlah besar secara efi… Kamu berlatih Node.js Backend Development Bootcamp dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai Node.js Backend Development Bootcamp?

Tidak diperlukan pengalaman sebelumnya. Node.js Backend Development Bootcamp di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.

Berapa lama pelajaran “Bekerja dengan Sistem Berkas & Aliran” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran Node.js Backend Development Bootcamp ini?

Ya. Setiap pelajaran Node.js Backend Development Bootcamp menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Pengantar Node.js & NPM
  2. Penjelasan Sistem Modul Node.js
  3. JavaScript Asinkron & Event Loop
  4. Bekerja dengan Sistem Berkas & Aliran
← Kembali ke Node.js Backend Development Bootcamp