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