mirror of
https://github.com/m-lamonaca/dev-notes.git
synced 2025-04-05 18:36:41 +00:00
Remove NodeJS & duplicate notes
This commit is contained in:
parent
d228cc1dfb
commit
91e715a608
16 changed files with 0 additions and 666 deletions
|
@ -1,26 +0,0 @@
|
|||
# Page.aspx.cs
|
||||
|
||||
```cs
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using System.Web.UI;
|
||||
using System.Web.UI.WebControls;
|
||||
|
||||
namespace Project
|
||||
{
|
||||
public partial class Default : System.Web.UI.Page
|
||||
{
|
||||
protected void Page_Load(object sender, EventArgs e)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
protected void Control_Event(object sender, EventArgs e)
|
||||
{
|
||||
// actions on event trigger
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
|
@ -1,58 +0,0 @@
|
|||
# Page.aspx
|
||||
|
||||
The fist loaded page is `Default.aspx` and its underlying code.
|
||||
|
||||
```html
|
||||
<!-- directive -->
|
||||
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Project.Default" %>
|
||||
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"> <!-- XML Namespace -->
|
||||
<head runat="server"> <!-- runat: handle as ASP code -->
|
||||
<title></title>
|
||||
</head>
|
||||
<body>
|
||||
<!-- web forms require a form tag to be the whole body -->
|
||||
<form id="form1" runat="server"> <!-- runat: handle as ASP code -->
|
||||
<div>
|
||||
</div>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## ASP.NET Directives
|
||||
|
||||
### Page Directive
|
||||
|
||||
```cs
|
||||
<%@ Page Language="C#" // define language used (can be C# or VB)
|
||||
AutoEventWireup="true" // automatically create and setup event handlers
|
||||
CodeBehind="Default.aspx.cs" // define the underlying code file
|
||||
Inherits="EmptyWebForm.Default" %>
|
||||
```
|
||||
|
||||
## Web Controls
|
||||
|
||||
```xml
|
||||
<asp:Control ID="" runat="server" ...></asp:Control>
|
||||
|
||||
<!-- Label: empty text will display ID, use empty space as text for empty label -->
|
||||
<asp:Label ID="lbl_" runat="server" Text=" "></asp:Label>
|
||||
<!-- TextBox -->
|
||||
<asp:TextBox ID="txt_" runat="server"></asp:TextBox>
|
||||
<!-- Button -->
|
||||
<asp:Button ID="btn_" runat="server" Text="ButtonText" OnClick="btn_Click" />
|
||||
<!-- HyperLink -->
|
||||
<asp:HyperLink ID="lnk_" runat="server" NavigateUrl="~/Page.aspx">LINK TEXT</asp:HyperLink>
|
||||
<!-- LinkButton: POstBackEvent reloads the page -->
|
||||
<asp:LinkButton ID="lbtHome" runat="server" PostBackUrl="~/Page.aspx" OnClick="lbt_Click">BUTTON TEXT</asp:LinkButton>
|
||||
<!-- Image -->
|
||||
<asp:Image ID="img_" runat="server" ImageUrl="~/Images/image.png"/>
|
||||
<!-- ImageButton -->
|
||||
<asp:ImageButton ID="imb_" runat="server" ImageUrl="~/Images/image.png" PostBackUrl="~/Page.aspx"/>
|
||||
|
||||
<!-- SqlSataSource; connection string specified in Web.config -->
|
||||
<asp:SqlDataSource ID="sds_" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SQL Query"></asp:SqlDataSource>
|
||||
```
|
|
@ -1,59 +0,0 @@
|
|||
# [Express](https://expressjs.com/)
|
||||
|
||||
## Installation
|
||||
|
||||
```ps1
|
||||
npm install express --save
|
||||
```
|
||||
|
||||
## [Application](https://expressjs.com/en/4x/api.html#app)
|
||||
|
||||
```js
|
||||
const express = require("express");
|
||||
|
||||
const app = express();
|
||||
const PORT = 5555;
|
||||
|
||||
// correctly serve static contents
|
||||
app.use(express.static("/route/for/static/files", "path/to/static/files/folder"));
|
||||
|
||||
// HTTP GET
|
||||
app.get("/<route>:<param>", (req, res) => {
|
||||
console.log(`${req.connection.remoteAddress} requested ${req.url}`);
|
||||
});
|
||||
|
||||
// HTTP POST
|
||||
app.post("/<route>:<param>", (req, res) => {
|
||||
console.log(`${req.connection.remoteAddress} posted to ${req.url}`);
|
||||
});
|
||||
|
||||
// responds to all HTTP verbs
|
||||
app.all("/<route>:<param>", (req, res, next) => {
|
||||
next(); // handle successive matching request (valid also on .get() & .post())
|
||||
});
|
||||
|
||||
let server = app.listen(PORT, () => {
|
||||
console.log(`Express server listening at http://localhost:${PORT}`);
|
||||
});
|
||||
|
||||
server.on("error", () => {
|
||||
server.close();
|
||||
});
|
||||
```
|
||||
|
||||
## [Response](https://expressjs.com/en/4x/api.html#res)
|
||||
|
||||
```js
|
||||
Response.send([body]); // Sends the HTTP response.
|
||||
Response.sendFile(path); // Transfers the file at the given path.
|
||||
Response.json(body); // Sends a JSON response.
|
||||
Response.redirect([status,] path); // Redirects to the URL derived from the specified path, with specified status
|
||||
Response.end(); // Ends the response process
|
||||
```
|
||||
|
||||
## [Request](https://expressjs.com/en/4x/api.html#req)
|
||||
|
||||
```js
|
||||
Request.params.<param> // query params obj (GET)
|
||||
Request.body.<param> // body params (POST)
|
||||
```
|
|
@ -1,68 +0,0 @@
|
|||
# Node.js
|
||||
|
||||
Asynchronous JavaScript Engine
|
||||
|
||||
## Syllabus
|
||||
|
||||
Moduli:
|
||||
|
||||
- nvm, npm cli
|
||||
- tutti moduli standard
|
||||
- alcuni da npm (express?, cors?, nodemon?)
|
||||
|
||||
## NVM
|
||||
|
||||
### Windows
|
||||
|
||||
```ps1
|
||||
nvm list # show installed node versions
|
||||
nvm list available # list installable versions of node
|
||||
|
||||
nvm install <version> # install a version of node
|
||||
nvm install latest # install the latest version of node
|
||||
|
||||
nvm use <version> # set <version> as default one
|
||||
|
||||
nvm uninstall <version> # uninstall a version of node
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
```bash
|
||||
nvm ls # show installed node versions
|
||||
nvm ls-remote # list installable versions of node
|
||||
|
||||
nvm install <version> # install a version of node
|
||||
nvm install node # install the latest version of node
|
||||
nvm install --lts # install the latest LTS version of node
|
||||
|
||||
nvm use <version> # set <version> as default one
|
||||
|
||||
nvm uninstall <version> # uninstall a version of node
|
||||
```
|
||||
|
||||
## NPM
|
||||
|
||||
```ps1
|
||||
npm init # init a project
|
||||
npm install <module> # install a module as global
|
||||
npm install <module> -P|--save-prod # install a module as local (aka --save)
|
||||
npm install <module> -D|--save-dev # install a module as local dev dependency
|
||||
```
|
||||
|
||||
## Imports
|
||||
|
||||
```js
|
||||
const pkg = require("module"); // load the file as JS object with an alias
|
||||
const { component } = require("module"); // load only a component of the module (can lead to name collision)
|
||||
const alias = require("module").component // set alias for component
|
||||
```
|
||||
|
||||
## Exports
|
||||
|
||||
```js
|
||||
// definitions
|
||||
|
||||
module.exports = <variable/method/class/expression>; // dafoult export
|
||||
module.exports.exported_name = <variable/method/class/expression>;
|
||||
```
|
|
@ -1,22 +0,0 @@
|
|||
# Child Process Module
|
||||
|
||||
## Spawning
|
||||
|
||||
```js
|
||||
child_process.spawn(command, args, options); // spawn a child process
|
||||
|
||||
// On Windows, setting options.detached to true makes it possible for the child process to continue running after the parent exits
|
||||
child_process.spawn(command, args, {
|
||||
detached: true
|
||||
});
|
||||
```
|
||||
|
||||
## Using The System Shell
|
||||
|
||||
```js
|
||||
exec("command args", {'shell':'powershell.exe'}, (err, stdout, stderr) => {
|
||||
|
||||
});
|
||||
|
||||
execSync("command args", {'shell':'powershell.exe'});
|
||||
```
|
|
@ -1,50 +0,0 @@
|
|||
# Cluster Module
|
||||
|
||||
A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a **cluster of Node.js processes** to handle the load.
|
||||
|
||||
The cluster module allows easy creation of child processes that all share server ports.
|
||||
|
||||
```js
|
||||
const cluster = require('cluster');
|
||||
const http = require('http');
|
||||
const numCPUs = require('os').cpus().length;
|
||||
|
||||
if (cluster.isMaster) {
|
||||
console.log(`Master ${process.pid} is running`);
|
||||
|
||||
// Fork workers. (Spawn a new worker process)
|
||||
for (let i = 0; i < numCPUs; i++) {
|
||||
cluster.fork();
|
||||
}
|
||||
|
||||
cluster.on('exit', (worker, code, signal) => {
|
||||
console.log(`worker ${worker.process.pid} died`);
|
||||
cluster.fork();
|
||||
});
|
||||
|
||||
} else {
|
||||
// Workers can share any TCP connection
|
||||
// In this case it is an HTTP server
|
||||
http.createServer((req, res) => {
|
||||
res.writeHead(200);
|
||||
res.end('hello world\n');
|
||||
}).listen(8000);
|
||||
|
||||
console.log(`Worker ${process.pid} started`);
|
||||
}
|
||||
```
|
||||
|
||||
## Cluster VS Worker Threads
|
||||
|
||||
Cluster (multi-processing):
|
||||
|
||||
- One process is launched on each CPU and can communicate via IPC.
|
||||
- Each process has it's own memory with it's own Node (v8) instance. Creating tons of them may create memory issues.
|
||||
- Great for spawning many HTTP servers that share the same port b/c the master main process will multiplex the requests to the child processes.
|
||||
|
||||
Worker Threads (multi-threading):
|
||||
|
||||
- One process total
|
||||
- Creates multiple threads with each thread having one Node instance (one event loop, one JS engine). Most Node API's are available to each thread except a few. So essentially Node is embedding itself and creating a new thread.
|
||||
- Shares memory with other threads (e.g. SharedArrayBuffer)
|
||||
- Great for CPU intensive tasks like processing data or accessing the file system. Because NodeJS is single threaded, synchronous tasks can be made more efficient with workers
|
|
@ -1,34 +0,0 @@
|
|||
# UDP Module
|
||||
|
||||
```js
|
||||
const socket = dgram.createSocket("udp4"); // connect to network interface
|
||||
|
||||
socket.on("error", (err) => { /* handle error */ });
|
||||
socket.on("message", (msg, rinfo) => {});
|
||||
socket.on("end", () => {});
|
||||
|
||||
socket.bind(port); // listen to port
|
||||
socket.on('listening', () => {});
|
||||
|
||||
socket.send(message, port, host, (err) => { /* handle error */ });
|
||||
```
|
||||
|
||||
## Multicasting
|
||||
|
||||
```js
|
||||
const socket = dgram.createSocket({ type: "udp4", reuseAddr: true });
|
||||
// When reuseAddr is true socket.bind() will reuse the address, even if another process has already bound a socket on it.
|
||||
|
||||
const multicastPort = 5555;
|
||||
const multicastAddress = "239.255.255.255"; // whatever ip
|
||||
|
||||
socket.bind(multicastPort);
|
||||
|
||||
socket.on("listening", () => {
|
||||
socket.addMembership(multicastAddress);
|
||||
})
|
||||
|
||||
socket.on("message", (msg, rinfo) => {
|
||||
console.log(`Got: "${msg.toString()}" from ${rinfo.address}`);
|
||||
});
|
||||
```
|
|
@ -1,35 +0,0 @@
|
|||
# Events Module
|
||||
|
||||
Much of the Node.js core API is built around an idiomatic *asynchronous event-driven architecture* in which certain kinds of objects (**emitters**) emit *named events* that cause `Function` objects (**listeners**) to be called.
|
||||
|
||||
All objects that emit events are instances of the `EventEmitter` class. These objects expose an `eventEmitter.on()` function that allows one or more functions to be attached to named events emitted by the object. Typically, event names are camel-cased strings but any valid JavaScript property key can be used.
|
||||
|
||||
When the EventEmitter object emits an event, all of the functions attached to that specific event are called *synchronously*. Any values returned by the called listeners are *ignored and discarded*.
|
||||
|
||||
```js
|
||||
const EventEmitter = require("events");
|
||||
|
||||
class CustomEmitter extends EventEmitter {} ;
|
||||
|
||||
const customEmitterObj = new CustomEmitter();
|
||||
|
||||
// add event listener
|
||||
customEmitterObj.on("event", (e) => {
|
||||
// e contains event object
|
||||
})
|
||||
|
||||
// single-use event listener (execute and remove listener)
|
||||
customEmitterObj.once("event", (e) => {
|
||||
// e contains event object
|
||||
})
|
||||
|
||||
customEmitterObj.removeListener("event", callback);
|
||||
customEmitterObj.removeAllListeners("event");
|
||||
|
||||
customEmitterObj.emit("event");
|
||||
customEmitterObj.emit("event", { /* event object */ });
|
||||
|
||||
customEmitterObj.eventNames(); // string[] of the events it listens to
|
||||
customEmitterObj.listenerCount("event"); // num of listeners for an event
|
||||
customEmitterObj.listeners(); // Function[], handlers of the events
|
||||
```
|
|
@ -1,102 +0,0 @@
|
|||
# fs (FIle System) Module
|
||||
|
||||
Async versions can access file at the same time which can lead to conflicts in operations, errors can be handled in callback.
|
||||
Sync versions cannot interfere with each other, errors cause exceptions, handle in try-catch.
|
||||
|
||||
## Files
|
||||
|
||||
### Creating & Deleting Files
|
||||
|
||||
```js
|
||||
fs.writeFile(file, data, encoding="utf8", mode=0o666, (err) => {}); // create a file (async)
|
||||
fs.writeFileSync(file, data, encoding="utf8", mode=0o666); // create a file (sync)
|
||||
|
||||
// remove file
|
||||
fs.unlink(path, callback); // delete a file (async)
|
||||
fs.unlinkSync(path); // delete a file (sync)
|
||||
|
||||
// remove file or directory
|
||||
fs.rm(path, force=false, recursive=false, (err) => {});
|
||||
fs.rmSync(path, force=false, recursive=false);
|
||||
|
||||
// rename a file, if oldPath is a directory an error will be rised
|
||||
fs.rename(oldPath, newPath, (err) => {});
|
||||
fs.renameSync(oldPath, newPath);
|
||||
```
|
||||
|
||||
### Writing & Reading a File
|
||||
|
||||
```js
|
||||
// append contents to a file
|
||||
fs.appendFile(file, data, encoding="utf8", mode=0o666, (err) => {});
|
||||
fs.appendFileSync(file, data, encoding="utf8", mode=0o666);
|
||||
|
||||
// write contents into a file
|
||||
fs.write(fd, string, position, encoding="utf8", (err) => {});
|
||||
fs.writeSync(fd, string, position, encoding="utf8"); // returns num of bytes written
|
||||
|
||||
// read file contents
|
||||
fs.readFile(path, (err, data) => {});
|
||||
fs.readFileSync(path); // returns contents of the file
|
||||
```
|
||||
|
||||
### Managing Links
|
||||
|
||||
```js
|
||||
// make a new name for a file
|
||||
fs.link(existingPath, newPath, (err) => {});
|
||||
fs.linkSync(existingPath, newPath);
|
||||
|
||||
// make a new name for a file (symlink)
|
||||
fs.symlink(target, path, (err) => {});
|
||||
fs.symlink(target, path);
|
||||
```
|
||||
|
||||
### Managing Permissions
|
||||
|
||||
## Directories & `fs.Dir`
|
||||
|
||||
### Creating & Deleting Directories
|
||||
|
||||
```js
|
||||
// create a directory
|
||||
fs.mkdir(path, mode=0o777, (err) => {});
|
||||
fs.mkdirSync(path, mode=0o777);
|
||||
|
||||
// remove a directory
|
||||
fs.rmdir(path, recursive=false, (err) => {});
|
||||
fs.rmdirSync(path, recursive=false;
|
||||
```
|
||||
|
||||
### Reading Directory Contents
|
||||
|
||||
```js
|
||||
// read directory contents
|
||||
fs.readdir(path, (err, files) => {}); // files is string[]
|
||||
fs.readdir(path, { withFileTypes: true }, (err, files) => {}); // files is Dirent[]
|
||||
fs.readdirSync(path); // returns string[] of files/directories
|
||||
fs.readdirSync(path, { withFileTypes: true }); // returns Dirent[] of files/directories
|
||||
```
|
||||
|
||||
### `fs.Dir`
|
||||
|
||||
```js
|
||||
// construct an fs.Dir object from an existing path
|
||||
fs.opendir(path, (err, dir) => {});
|
||||
fs.opendirSync(path); // return a fs.Dir object
|
||||
```
|
||||
|
||||
## fs.Stats
|
||||
|
||||
### Obtaining
|
||||
|
||||
```js
|
||||
fs.stat(path, {bigint: true}, (err, stats) => {});
|
||||
fs.statSync(path, {bigint: true}); // returns fs.Stats
|
||||
|
||||
fs.lstat(path, {bigint: true}, (err, stats) => {});
|
||||
fs.lstatSync(path, {bigint: true}); // returns fs.Stats
|
||||
|
||||
fs.fstat(path, {bigint: true}, (err, stats) => {});
|
||||
fs.fstatSync(path, {bigint: true}); // returns fs.Stats
|
||||
```
|
|
@ -1,80 +0,0 @@
|
|||
# HTTP(S) Module
|
||||
|
||||
## HTTPS(S) IncomingMessage (request)
|
||||
|
||||
### Making a request
|
||||
|
||||
```js
|
||||
https.request(
|
||||
{
|
||||
host: "www.website.com",
|
||||
method: "GET", // POST, ...
|
||||
path: "/page/?param=value"
|
||||
},
|
||||
(response) => { // response is IncomingMessage
|
||||
// do stuff
|
||||
}
|
||||
).end();
|
||||
```
|
||||
|
||||
### Request Methods & Properties
|
||||
|
||||
```js
|
||||
IncomingMessage.headers
|
||||
IncomingMessage.statusCode
|
||||
IncomingMessage.statusMessage
|
||||
IncomingMessage.url
|
||||
```
|
||||
|
||||
## HTTPS(S) ServerResponse (response)
|
||||
|
||||
### Response Methods & Properties
|
||||
|
||||
```js
|
||||
ServerResponse.writeHead(statusCode[, statusMessage][, headers]);
|
||||
```
|
||||
|
||||
## HTTP(S) Server
|
||||
|
||||
### Creating a server
|
||||
|
||||
```js
|
||||
const PORT = 8123;
|
||||
|
||||
// req is IncomingMessage
|
||||
// res is ServerResponse
|
||||
const server = http.createServer((req, res) => {
|
||||
|
||||
let body = "<html></html>"
|
||||
|
||||
res.writeHead(200, {
|
||||
"Content-Length": Buffer.byteLength(body),
|
||||
"Content-Type": "text/html; charset=utf8"
|
||||
});
|
||||
|
||||
res.end(body);
|
||||
|
||||
});
|
||||
|
||||
server.listen(PORT);
|
||||
```
|
||||
|
||||
### Reading a request search params
|
||||
|
||||
```js
|
||||
const http = require("http");
|
||||
const url = require("url");
|
||||
|
||||
const PORT = 8123;
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
let url = new URL(req.url, "http://" + req.headers.host);
|
||||
let params = url.searchParams;
|
||||
|
||||
// ...
|
||||
|
||||
});
|
||||
|
||||
console.log("Listening on port: " + PORT);
|
||||
server.listen(PORT);
|
||||
```
|
|
@ -1,26 +0,0 @@
|
|||
# Net Module (Connection Oriented Networking - TCP/IP)
|
||||
|
||||
## Server (`net.Server`)
|
||||
|
||||
```js
|
||||
const net = require('net');
|
||||
|
||||
const server = net.createServer((socket) => { /* connect listener */ });
|
||||
|
||||
server.on('error', (err) => {
|
||||
// handle error
|
||||
});
|
||||
|
||||
server.listen(8124, () => { }); // listen for connection
|
||||
```
|
||||
|
||||
## Sockets (`net.Socket`)
|
||||
|
||||
```js
|
||||
|
||||
const client = net.createConnection({ host: "127.0.0.1", port: 8124 }, () => { /* 'connect' listener. */ });
|
||||
|
||||
socket.on("data", (buffer) => { /* operate on input buffer */ });
|
||||
socket.on("error", (err) => { /* handle error */ });
|
||||
socket.on("end", () => {}); // client disconnection
|
||||
```
|
|
@ -1,20 +0,0 @@
|
|||
# OS Module
|
||||
|
||||
## Information
|
||||
|
||||
```js
|
||||
os.arch(); // CPU Architecture
|
||||
os.platform(); // OS platform (aix, darwin, freebsd, linux, openbsd, sunos, win32)
|
||||
os.type(); // OS name (Linux, Windows_NT, )
|
||||
|
||||
os.release(); // OS release number
|
||||
os.version(); // OS kernel version
|
||||
|
||||
os.tmpdir(); // OS Temp directory
|
||||
os.homedir(); // CUrrent user home directory
|
||||
|
||||
os.hostname(); // PC Name
|
||||
|
||||
os.cpus(); // Array of CPU info
|
||||
os.networkInterfaces(); // Array of Network Interfaces info
|
||||
```
|
|
@ -1,5 +0,0 @@
|
|||
# Path Module
|
||||
|
||||
```js
|
||||
path.join("folder1", "folder2", "filename"); // WIN: folder1\folder2\filename - LINUX: folder1/folder2/filename
|
||||
```
|
|
@ -1,27 +0,0 @@
|
|||
# Process Module
|
||||
|
||||
Provides information about, and control over, the current Node.js process
|
||||
|
||||
## Properties
|
||||
|
||||
```js
|
||||
process.argv // string[] containing the command-line arguments passed when the Node.js process was launched
|
||||
process.pid // PID of the process
|
||||
process.env // list of ENV Variables
|
||||
process.platform // identifier of the OS
|
||||
process.arch // processor architecture
|
||||
```
|
||||
|
||||
## Functions
|
||||
|
||||
```js
|
||||
process.resourceUsage(); // resource usage for the current process
|
||||
process.memoryUsage(); // memory usage of the Node.js process measured in bytes
|
||||
process.exit(code); // terminate the process synchronously with an exit status of code
|
||||
```
|
||||
|
||||
## Events
|
||||
|
||||
```js
|
||||
process.on("event", (code) => { });
|
||||
```
|
|
@ -1,16 +0,0 @@
|
|||
# Url Module
|
||||
|
||||
`http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash`
|
||||
|
||||

|
||||
|
||||
## Basics
|
||||
|
||||
```js
|
||||
|
||||
const url = new URL('/foo', 'https://example.org/');
|
||||
|
||||
URL.searchParams
|
||||
URL.searchParams.get("queryparam");
|
||||
URL.searchParams.has("queryparam");
|
||||
```
|
|
@ -1,38 +0,0 @@
|
|||
# Worker Threads Module
|
||||
|
||||
The `worker_threads` module enables the use of threads that execute JavaScript in parallel.
|
||||
|
||||
Workers (threads) are useful for performing CPU-intensive JavaScript operations. They do not help much with I/O-intensive work. The Node.js built-in asynchronous I/O operations are more efficient than Workers can be.
|
||||
|
||||
Unlike `child_process` or `cluster`, `worker_threads` can *share* memory. They do so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer` instances.
|
||||
|
||||
```js
|
||||
const { Worker, isMainThread } = require("worker_threads");
|
||||
|
||||
if(isMainThread){
|
||||
console.log("Main Thread");
|
||||
|
||||
// start new inner thread executing this file
|
||||
new Worker(__filename);
|
||||
}
|
||||
else
|
||||
{
|
||||
// executed by inner threads
|
||||
console.log("Inner Thread Starting");
|
||||
}
|
||||
```
|
||||
|
||||
## Cluster VS Worker Threads
|
||||
|
||||
Cluster (**multi-processing**):
|
||||
|
||||
- One process is launched on each CPU and can communicate via IPC.
|
||||
- Each process has it's own memory with it's own Node (v8) instance. Creating tons of them may create memory issues.
|
||||
- Great for spawning many HTTP servers that share the same port b/c the master main process will multiplex the requests to the child processes.
|
||||
|
||||
Worker Threads (**multi-threading**):
|
||||
|
||||
- One process total
|
||||
- Creates multiple threads with each thread having one Node instance (one event loop, one JS engine). Most Node API's are available to each thread except a few. So essentially Node is embedding itself and creating a new thread.
|
||||
- Shares memory with other threads (e.g. SharedArrayBuffer)
|
||||
- Great for CPU intensive tasks like processing data or accessing the file system. Because NodeJS is single threaded, synchronous tasks can be made more efficient with workerss
|
Loading…
Add table
Reference in a new issue