refactor: finish moving ssh-* scripts to own installers
[webi-installers/.git] / node / README.md
1 ---
2 title: Node.js
3 homepage: https://nodejs.org
4 tagline: |
5   Node.jsĀ® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
6 ---
7
8 To update or switch versions, run `webi node@<tag>`. \
9 (you can use `@lts` for long-term support, `@beta` for pre-releases, or `@x.y.z`
10 for a specific version)
11
12 ## Cheat Sheet
13
14 > Node is great for simple, snappy HTTP(S) servers, and for stitching APIs
15 > together with minimal fuss or muss.
16
17 Installing node via webi will:
18
19 - pick a compatible version from the
20   [Node Releases API](https://nodejs.org/dist/index.tab)
21 - download and unpack to `$HOME/.local/opt/node/`
22 - update your `PATH` in `$HOME/.config/envman/PATH.env`
23 - run `npm config set scripts-prepend-node-path=true`
24   - (prevents conflicts with other installed node versions)
25 - absolutely leave system file permissions alone
26   - (no dreaded `sudo npm` permission errors)
27
28 ### Hello World
29
30 ```bash
31 node -e 'console.log("Hello, World!")'
32 > Hello, World!
33 ```
34
35 ### A Simple Web Server
36
37 `server.js`:
38
39 ```bash
40 var http = require('http');
41 var app = function (req, res) {
42   res.end('Hello, World!');
43 };
44 http.createServer(app).listen(8080, function () {
45   console.info('Listening on', this.address());
46 });
47 ```
48
49 ```bash
50 node server.js
51 ```
52
53 ### Generate a Secure Random Key
54
55 This generates a hex-encoded 128-bit random key.
56
57 ```bash
58 node -p 'crypto.randomBytes(16).toString("hex")'
59 ```
60
61 This generates a url-safe base64 256-bit random key.
62
63 ```bash
64 node -p 'crypto.randomBytes(32).toString("base64")
65             .replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "")'
66 ```
67
68 ### An Express App
69
70 ```bash
71 mkdir my-server
72 pushd my-server/
73 npm init
74 npm install --save express
75 ```
76
77 `app.js`:
78
79 ```js
80 'use strict';
81
82 var express = require('express');
83 var app = express();
84
85 app.use('/', function (req, res, next) {
86   res.end('Hello, World!');
87 });
88
89 module.exports = app;
90 ```
91
92 `server.js`:
93
94 ```js
95 'use strict';
96
97 var http = require('http');
98 var app = require('./app.js');
99
100 http.createServer(app).listen(8080, function () {
101   console.info('Listening on', this.address());
102 });
103 ```
104
105 ```bash
106 npm start
107 ```