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