• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Usage and example
2
3## Usage
4
5<!--introduced_in=v0.10.0-->
6
7<!--type=misc-->
8
9`node [options] [V8 options] [script.js | -e "script" | - ] [arguments]`
10
11Please see the [Command-line options][] document for more information.
12
13## Example
14
15An example of a [web server][] written with Node.js which responds with
16`'Hello, World!'`:
17
18Commands in this document start with `$` or `>` to replicate how they would
19appear in a user's terminal. Do not include the `$` and `>` characters. They are
20there to show the start of each command.
21
22Lines that don't start with `$` or `>` character show the output of the previous
23command.
24
25First, make sure to have downloaded and installed Node.js. See
26[Installing Node.js via package manager][] for further install information.
27
28Now, create an empty project folder called `projects`, then navigate into it.
29
30Linux and Mac:
31
32```console
33$ mkdir ~/projects
34$ cd ~/projects
35```
36
37Windows CMD:
38
39```console
40> mkdir %USERPROFILE%\projects
41> cd %USERPROFILE%\projects
42```
43
44Windows PowerShell:
45
46```console
47> mkdir $env:USERPROFILE\projects
48> cd $env:USERPROFILE\projects
49```
50
51Next, create a new source file in the `projects`
52folder and call it `hello-world.js`.
53
54Open `hello-world.js` in any preferred text editor and
55paste in the following content:
56
57```js
58const http = require('node:http');
59
60const hostname = '127.0.0.1';
61const port = 3000;
62
63const server = http.createServer((req, res) => {
64  res.statusCode = 200;
65  res.setHeader('Content-Type', 'text/plain');
66  res.end('Hello, World!\n');
67});
68
69server.listen(port, hostname, () => {
70  console.log(`Server running at http://${hostname}:${port}/`);
71});
72```
73
74Save the file, go back to the terminal window, and enter the following command:
75
76```console
77$ node hello-world.js
78```
79
80Output like this should appear in the terminal:
81
82```console
83Server running at http://127.0.0.1:3000/
84```
85
86Now, open any preferred web browser and visit `http://127.0.0.1:3000`.
87
88If the browser displays the string `Hello, World!`, that indicates
89the server is working.
90
91[Command-line options]: cli.md#options
92[Installing Node.js via package manager]: https://nodejs.org/en/download/package-manager/
93[web server]: http.md
94