# A Quick Look at Node.js

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/Node.js-note/>). I am continuously working to improve the translation.

This article mainly references:

- [Node.js - JavaScript Tutorial - Liao Xuefeng's Official Website](https://liaoxuefeng.com/books/javascript/nodejs/index.html)
- [Node.js Basics - SAST skill docs](https://docs.net9.org/languages/node.js/)

## What is Node.js

First, let's understand + review how JavaScript runs:

JavaScript code needs a **runtime** to run, and **runtime = engine + API + event loop mechanism**:

- Engine: the program responsible for compilation, interpretation, and memory management
- API: for example, browsers provide WebAPIs, the most typical of which is the DOM API
- Event loop mechanism: as we mentioned before, JavaScript is single-threaded; the event loop mechanism is the way asynchrony is implemented

So-called Node.js is a **runtime** based on the V8 engine.

## Use Cases for Node.js

### Backend

With Node.js, you can write backends in JavaScript / TypeScript, because Node.js provides modules such as `fs` (file system), `net` (networking), and `http` (server). Meanwhile, the efficiency of the V8 engine allows programs based on Node.js to achieve extremely high execution efficiency.

### Frontend

Of course, Node.js can also be used for frontend development. Although the runtime environment for the frontend is the browser rather than Node.js, Node.js provides mechanisms that are essentially the same as the browser's, while also offering capabilities such as compilation and bundling. Therefore, in frontend development, TypeScript is often used for development; after compilation and bundling are completed in the Node.js environment, the generated bundle files are deployed to the frontend. Common frameworks include React.js, Vue.js, etc.

### Client Applications

Node.js can also be used to write native applications through frameworks such as React Native and Electron, providing a development experience similar to web development.

## Running Node.js

Running Node.js is very similar to Python; you can use the REPL (read-eval-print-loop) approach.

- REPL: type `node` in the command line to open an interactive interface similar to typing `python`.
- Script: `node xxx.js` runs a script

## Node.js Modularity

Why didn't the previous JavaScript chapter mention things like package management?

It's because in frontend development, modules are imported in the following ways:

- Bundle all the modules you need via Node.js

- Import via CDN

    ```html
    <script src="https://xxx.js"></script>
    ```

    However, such an import adds a property `xxx` to the browser's global object `window`, which is a bit polluting. Therefore, we use ES6 Modules for package management.

### ES6 Module

Some APIs — just look at the examples:

```JavaScript
// 文件名 export.js
// 导出值 value
export { value };
// 导出值 value 并重命名为 aliasNameOfValue
export { value as aliasNameOfValue };
// 以下两句等价
export { value as default };
export default value;

// 对于 TypeScript，可以通过以下方式导出类型
// 二者的区别是前一个可以确保这一行内容不会出现在编译结果中
export type { type };
export { type };
```

## npm

That is, **Node.js package manager**, the default package management tool for Node.js.

### Module Resolution in Node.js

```JavaScript
import fs from 'fs';           // 内置文件系统模块
import express from 'express'; // 一个 web 服务器模块
```

This involves some resolution priorities and logic:

> - For built-in modules, their locations are already determined at the compilation stage, so there is no addressing problem;
> - For modules with a specified path:
>     1. First, look up the file itself, trying default extensions in the order `.js`, `.node`, `.json`;
>     2. Then, try treating it as a folder name, look up the `package.json` in that folder, and reference the file specified by its `main` field;
>     3. Finally, try treating it as a folder name and look up the `index` file in that folder, with the same default extension logic as c.
> - For other modules without a specified path, i.e., modules installed via a package manager, Node.js will try to look them up in the `node_modules` folder under the current folder; if the lookup fails, it will then search the (possible) `node_modules` folders in parent directories one by one.

### Other Package Managers

| Operation | npm | yarn | pnpm |
| :----------------------------- | :-------------------------- | :----------------------- | :----------------------- |
| Install dependencies automatically | `npm install` | `yarn install / yarn` | `pnpm install` |
| Add a dependency | `npm install lodash` | `yarn add lodash` | `pnpm add lodash` |
| Add a dev dependency (not for production) | `npm install -D typescript` | `yarn add -D typescript` | `pnpm add -D typescript` |
| Remove a dependency | `npm uninstall lodash` | `yarn remove lodash` | `pnpm remove lodash` |
| Run the `start` script | `npm run start` | `yarn start` | `pnpm start` |
