---
# System prepended metadata

title: NodeJS Learning

---

# NodeJS Learning

## Event Listener
```javascript=
// Create event listener
emitter.on(event, function(arg1, arg2))

// trigger the event
emitter.emit(event, [arg1], [arg2])
```

### Modules
> `fs` `path` `http`
 
- `fs`
    - `fs.writeFile(filePath, 'what to write in', callback)`
    - `fs.readFile()`
    - `fs.mkdir(file, {}, callback)`
    - `fs.rename()`
```javascript=
fs.readFile(filePath, (data, err) => {})` 
```

- `path`
```javascript=
path.join(__dirname, '..', '..')
path.extname(filePath)
```

- `http`

- Use ES6 instead
```javascript=
import { URL } from 'url'; // in Browser, the URL in native accessible on window

const __filename = new URL('', import.meta.url).pathname;
const __dirname = new URL('.', import.meta.url).pathname;
```


## Request and Response
- `res.end('')`
- `res.writeHead(status, {'Content-Type': 'text/html'})`
- `req.url`

## Mixed together
```javascript=
const server = http.createServer((req, res) => {
    // Build filePath
    const filePath = path.join(
        __dirname,
        "public",
        req.url === "/" ? "index.html" : req.url
    );
    console.log(filePath);

    // Extension
    let extname = path.extname(filePath);

    // Initial contentType
    let contentType = "text/html";

    switch (extname) {
        case ".js":
            contentType = "text/js";
            break;
        case ".css":
            contentType = "text/css";
            break;
        case ".json":
            contentType = "application/json";
            break;
        case ".jpg":
            contentType = "img/jpg";
            break;
        case ".png":
            contentType = "img/png";
            break;
    }

    // Read file
    fs.readFile(filePath, (err, data) => {
        if (err) {
            // Page not found
            if (err.code == "ENOENT") {
                fs.readFile(
                    path.join(__dirname, "public", "404.html"),
                    (err, data) => {
                        res.writeHead(200, { "Content-Type": "text/html" });
                        res.end(data, "utf-8");
                    }
                );
            } else {
                // Some Server Error
                res.writeHead(500);
                res.end(`Server Error ${err.code}`);
            }
        } else {
            // Success
            res.writeHead(200, { "Content-Type": contentType });
            res.end(data, "utf-8");
        }
    });
})
```


