Butuh Data Cepat? Begini Cara Import Json di Node Js

Cara import JSON di Node.js tergantung kolom type di package.json. Pakai require('./data.json') kalau proyek masih CommonJS. Pakai import data from './data.json' with { type: 'json' } kalau proyek sudah "type": "module". Salah pilih sintaks, Node langsung melempar error modul.

Contoh file data.json minimal untuk latihan:

{"nama": "kopi", "stok": 12, "aktif": true}

Jawab Cepat Sesuai Sistem Modul Kamu

Cek dulu file package.json sebelum menulis kode.

  • Tanpa "type": "module": Node berjalan sebagai CommonJS, gunakan require.
  • Dengan "type": "module": Node berjalan sebagai ES Module, gunakan import plus with { type: 'json' }.
  • Node 22 ke atas menerima with. Node lama memakai assert { type: 'json' }, sekarang statusnya deprecated.

Kebutuhan Sebelum Import JSON

Siapkan tiga hal ini supaya path dan sintaks tidak bentrok.

  • Letakkan data.json satu folder dengan file yang memanggilnya, misalnya index.js dan data.json sama-sama di root.
  • Buka package.json dan lihat nilai type.
  • Pakai Node versi aktif LTS. Cek dengan node -v. Sintaks with butuh Node baru.

Langkah Import JSON di Node Js

1. Pakai require di CommonJS

const data = require('./data.json');
console.log(data.nama);

2. Pakai import statis di ES Module

import data from './data.json' with { type: 'json' };
console.log(data.stok);

3. Pakai dynamic import untuk file besar atau kondisional

const { default: data } = await import('./data.json', {
  with: { type: 'json' }
});

4. Pakai fs.readFileSync + JSON.parse bila perlu validasi

const fs = require('fs');
const raw = fs.readFileSync('./data.json', 'utf8');
const data = JSON.parse(raw);

Cara keempat berguna saat kamu ingin membungkus parsing dengan try/catch sendiri.

Perbandingan Cara Import JSON

Metode Cocok Untuk Catatan
require Proyek CommonJS Synchronous, paling ringkas
import statis Proyek ES Module Wajib pakai with type json
fs + JSON.parse Validasi manual Fleksibel atur encoding dan error

Pilih satu gaya modul untuk satu proyek. Mencampur require dan import tanpa strategi membuat maintenance sulit dan sering memicu ReferenceError: require is not defined.

Error yang Sering Muncul dan Perbaikannya

  • Cannot find module: path salah atau lupa ./. Samakan nama file dan huruf besar kecilnya.
  • ERR_IMPORT_ASSERTION_TYPE_MISSING: import JSON tanpa atribut tipe. Tambahkan with { type: 'json' }.
  • Unexpected token di JSON.parse: isi JSON tidak valid, misalnya koma ganda atau kutip tunggal. Validasi dulu memakai JSON linter.

FAQ

Apakah require bisa dipakai di ES Module?

Tidak langsung. Buat helper memakai createRequire dari modul module bila memang terpaksa.

Kenapa import JSON perlu with atau assert?

Node perlu penanda eksplisit agar file JSON tidak diperlakukan sebagai kode JavaScript.

Bagaimana baca JSON besar tanpa blocking?

Gunakan fs.createReadStream plus parser streaming atau pecah file menjadi beberapa bagian kecil.