Skip to main content

NodeJS 学习

(req: Request, res: Response) => {}

  • req: Request
    • req.params
    • req.body
  • res: Response
    • res.statusCode
    • res.setHeader(key: string, value: string)
    • res.end(value: string)

Node.js vs the Browser

Common point

Same programming language: Javascript

Packages

Browser

  • Dom
  • Web Platform APIs (Cookies)
  • document, window objects provided by the browser

Node.js

  • filesystem fc package
  • path package

Running Environment

Browser

  • You can't choose what browser your visitors will use.
  • You need to apply different compatibility of browser environments , you can use Balbel to transform your code to be ES5 compatible before shipping it to the browser.
  • Browser support CommonJS require() principally and limited import.

Node.js

  • You can control the environment, unlesss you are building an open source application that anyone can deploy anywhere, you know which version of Node.js you will run the application on.
  • Don't worring about the compatibility issue.
  • Node.js support both CommonJS require() and ES module system import.

The V8 Javascript Engine

Intro

V8 is the name of the JavaScript engine that powers Google Chrome.

V8 is the JavaScript engine i.e. it parses and executes JavaScript code. The DOM, and the other Web Platform APIs (they all makeup runtime environment) are provided by the browser.

info

V8 powers browser, server-side service and destop apps(Electron).

ECMA ES-262 standard

There're also other JS engines, All those engines implement the ECMA ES-262 standard, also called ECMAScript, the standard used by JavaScript.

Compilation

JavaScript is generally considered an interpreted language, but modern JavaScript engines no longer just interpret JavaScript, they compile it.

JavaScript is internally compiled by V8 with just-in-time (JIT) compilation to speed up the execution.

In this new world, compiling JavaScript makes perfect sense because while it might take a little bit more to have the JavaScript ready, once done it's going to be much more performant than purely interpreted code.

npm pcakage manager

Intro

npm is the standard package manager for Node.js.

info

Yarn and pnpm are alternatives to npm cli. You can check them out as well.

Packages

npm manages downloads of dependencies of your project.

Installing all dependencies

If a project has a package.json file, by running

npm install

it will install everything the project needs, in the node_modules folder, creating it if it's not existing already.

Installing a single package

You can also install a specific package by running

npm install <package-name>

npm install --save <package-name>
npm install --save-dev <package-name>
npm install --no-save <package-name>
npm install --save-optional <package-name>
npm install --no-optional <package-name>

Updating packages

Updating is also made easy, by running:

npm update

npm will check all packages for a newer version that satisfies your versioning constraints.

You can specify a single package to update as well:

npm update <package-name>

Versioning

In addition to plain downloads, npm also manages versioning, so you can specify any specific version of a package, or require a version higher or lower than what you need.

To handle compatibility issue with specific version of pacage, and many times you'll find that a library is only compatible with a major release of another library.

You can install a specific version of a package, by running:

npm install <package-name>@<version>

Running Tasks

The package.json file supports a format for specifying command line tasks that can be run by using:

npm run <task-name>

Set first package.json scripts attributs:

{
"scripts": {
"start-dev": "node lib/server-development",
"start": "node lib/server-production",
"watch": "webpack --watch --progress --colors --config webpack.conf.js",
"dev": "webpack --progress --colors --config webpack.conf.js",
"prod": "NODE_ENV=production webpack -p --config webpack.conf.js"
}
}

Usage of defined task:

npm run watch
npm run dev
npm run prod

Node.js, the difference between development and production

Node.js assumes it's always running in a development environment. You can signal Node.js that you are running in production by setting the NODE_ENV=production environment variable.

Setting the environment to production generally ensures that:

  • logging is kept to a minimum, essential level
  • more caching levels take place to optimize performance

You can use conditional statements to execute code in different environments:

if (process.env.NODE_ENV === "development") {
// ...
}
if (process.env.NODE_ENV === "production") {
// ...
}
if (["production", "staging"].includes(process.env.NODE_ENV)) {
// ...
}

For example, in an Express app, you can use this to set different error handlers per environment:

if (process.env.NODE_ENV === "development") {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
}
if (process.env.NODE_ENV === "production") {
app.use(express.errorHandler());
}

Node.js with TypeScript

TypeScript is a trendy open-source language maintained and developed by Microsoft. It's loved and used by a lot of software developers around the world.

Basically, it's a superset of JavaScript that adds new capabilities to the language. The most notable addition is static type definitions, something that is not present in plain JavaScript.

It makes our code more secure and robust by preventing many bugs before the code is even shipped - it catches problems during code development and integrates wonderfully with code editors like Visual Studio Code.

npm i -D typescript
npx tsc example.ts #compile it to Javascript
info

npx here stands for Node Package Execute. This tool allows us to run TypeScript's compiler without installing it globally.

tsc is the TypeScript compiler which will take our TypeScript code and compile it to JavaScript.

Some of the other benefits of TypeScript that are worth mentioning are that it can be adopted progressively, it helps making code more readable and understandable and it allows developers to use modern language features while shipping code for older Node.js versions.

Node.js with WebAssembly

Intro

WebAssembly is a high-performance assembly-like language (a binary file) that can be compiled from various languages, including C/C++, Rust, and AssemblyScript. Currently, it is supported by Chrome, Firefox, Safari, Edge, and Node.js!

In order to use WebAssembly, you need a .wasm binary file and a set of APIs to communicate with WebAssembly. Node.js provides the necessary APIs via the global WebAssembly object.

Key concepts

WebAssembly key concepts:

  • Module: A compiled WebAssembly binary, ie a .wasm file.
  • Memory: A resizable ArrayBuffer.
  • Table: A resizable typed array of references not stored in Memory.
  • Instance: An instantiation of a Module with its Memory, Table, and variables.

Generating WebAssembly Modules

Use tools like wabt, emscripten, wasm-pack, AssemblyScript to generate webAssembly modules.

How to use

Once you have a WebAssembly module, you can use the Node.js WebAssembly object to instantiate it.

// Assume add.wasm file exists that contains a single function adding 2 provided arguments
const fs = require("node:fs");
const wasmBuffer = fs.readFileSync("/path/to/add.wasm");
WebAssembly.instantiate(wasmBuffer).then((wasmModule) => {
// Exported function live under instance.exports
const { add } = wasmModule.instance.exports;
const sum = add(5, 6);
console.log(sum); // Outputs: 11
});

Interacting with the OS

WebAssembly modules cannot directly access OS functionality on its own. A third-party tool Wasmtime can be used to access this functionality. Wasmtime utilizes the WASI API to access the OS functionality.