Serve Static Files using Vanilla Node.js

Serve Static Files in Node.js http server

      • index.html
      • style.css
    • package.json
    • index.js
  • Maksudnya serve static files di sini adalah kita akan membuat server node.js yang akan mengirimkan file statis seperti html, css, js, dan gambar. Jadi, kita tidak perlu menggunakan server seperti Apache atau Nginx untuk mengirimkan file statis tersebut.

    Buat folder server-vanilla

    mkdir server-vanilla

    kalau foldernya udah ada ya pake nama folder lain juga boleh.

    Masuk ke folder server-vanilla

    cd server-vanilla

    Buat folder public

    mkdir public

    pastikan bikin folder public didalem folder server-vanilla, jangan di luarnya nanti gak bisa diakses hehehe.

    Buat file index.html

    kita bisa langsung bikin file html kedalam folder public dengan cara

    touch public/index.html

    bagi pengguna windows kalian bisa langsung saja membuat file baru pada visual studio code dengan nama file index.html pada folder public.

    disini kita pake simple html dulu aja yang isinya cuma

    <h1>Hello World</h1>

    kalau mau pake css yaa silahkan tambahkan cssnya di file index.html tadi. atau kalau mau terpisah juga boleh bikin file cssnya di folder public juga. Jangan lupa di link di file index.html nya.

    public/index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Server Vanilla</title>
      <link rel="stylesheet" href="style.css">
    </head>
    <body>
      <h1>Hello World</h1>
    </body>
    </html>
    public/style.css
    body {
      background-color: #000;
      color: #fff;
    }

    Buat file index.js

    touch index.js

    bagi pengguna windows kalian bisa langsung saja membuat file baru pada visual studio code dengan nama file index.js.

    init npm

    npm init --yes

    mau di otak atik isi package.json kaya author atau namanya terserah... bebasss

    Mengirimkan file statis dalam satu endpoint saja

    Di bawah ini berupa kode untuk menangani satu rute saja, yaitu rute /. Jadi, kalau kita buka localhost:4000 maka akan mengirimkan file index.html yang ada di folder public.

    index.js
    // import module http, fs, dan path
    // module http buat bikin server
    // module fs buat interaksi dengan file, di case ini kita hanya baca filenya
    // module path buat membantu kita mengarahkan ke path ke file yang kita mau
     
    const http = require('http');
    const fs = require('fs');
    const path = require('path');
     
    const server = http.createServer((req, res) => {
       // Cek kalau request buat ke url ("/")
      if (req.url === '/') {
        // Tentukan path ke file HTML yang kamu buat, kita taro file html di folder `public`
        const filePath = path.join(__dirname, 'public', 'index.html');
     
        // Baca file htmlnya
        fs.readFile(filePath, 'utf8', (err, data) => {
          if (err) {
            // Handle error kalau file tidak ditemukan
            res.writeHead(404, { 'Content-Type': 'text/plain' });
            res.end('404 Not Found');
          } else {
            // Kalau file ditemukan, set header response dengan content type html
            res.writeHead(200, { 'Content-Type': 'text/html' });
     
            // Kirim file yang diminta
            res.end(data);
          }
        });
      } else {
        // Kalau request bukan ke url ("/"), kirimkan response 404, karena yaa gak adaa rutenya
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 Not Found');
      }
    })
     
    const port = 4000; // Set port yang akan dibuka
    server.listen(port, () => {
      console.log(`Server is listening on port ${port}`);
    });

    Mengirimkan file statis dalam banyak endpoint

    Di bawah ini berupa kode untuk menangani banyak rute, jadi kalau kita buka localhost:4000 maka akan mengirimkan file index.html yang ada di folder public, kalau kita buka localhost:4000/about maka akan mengirimkan file about.html yang ada di folder public.

    index.js
    const http = require('http');
    const fs = require('fs');
    const path = require('path');
     
    const server = http.createServer((req, res) => {
      // Dengan menggunakan regex kita filter url request tanpa trailing slash '/' dan leading slash '/'
      const requestedUrl = req.url.replace(/^\/+|\/+$/g, '');
     
      // Agar request lebih fleksibel kita bisa hilangkan ekstensi .html
      const cleanUrl = requestedUrl.replace(/\.html$/, '');
     
      // Define the root directory where your HTML files are stored
      const rootDirectory = path.join(__dirname, 'public');
     
      // Buat path lengkap ke file yang diminta
      const filePath = path.join(rootDirectory, cleanUrl + '.html');
     
      // Cek dulu apakah file yang diminta ada
      fs.access(filePath, fs.constants.F_OK, (err) => {
        if (!err) {
          // kalau file yang diminta ada, maka baca file tersebut
          fs.readFile(filePath, (err, data) => {
            if (err) {
              // apabila terjadi error dalam membaca file, mengirimkan error
              res.writeHead(500, { 'Content-Type': 'text/plain' });
              res.end('500 Internal Server Error');
            } else {
              // Tentukan `content Type` berdasarkan ekstensi file
              const fileExtension = path.extname(filePath);
              const contentType = {
                '.html': 'text/html',
                '.css': 'text/css',
                '.js': 'application/javascript',
                // kita bisa tambahkan ekstensi lainnya jika dibutuhkan
              }[fileExtension] || 'text/plain';
     
              // Kita perlu untuk memberitahu browser bahwa response yang kita kirimkan adalah file statis
              res.writeHead(200, { 'Content-Type': contentType });
     
              // Kirim file yang diminta
              res.end(data);
            }
          });
        } else {
          // Ketika file yang diminta tidak ada, kirimkan response 404
          res.writeHead(404, { 'Content-Type': 'text/plain' });
          res.end('404 Not Found');
        }
      });
    });
     
    const port = 4000; // Set port yang akan dibuka
    server.listen(port, () => {
      console.log(`Server is listening on port ${port}`);
    });