This code is a direct copy of the code found on the Express.js site under Getting Started. I just followed installing and hello world from there to get a basic server up and running.
(index.js file
)
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port ' + port + '!');
});
To run this code (assuming you have followed the installing
tutorial mentioned above and have express
installed properly via npm
) you should have node
installed and then from the command line you can run
node index.js
Now, if you want to be able to run this server from any custom port, you can use process.env.port
, like so
(index.js file
)
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log('Example app listening on port ' + port + '!');
});
Notice the new port
variable we have defined and the chante to the app.listen
function.
It will allow you to set a custom port if you choose
or default back to 3000
if you do not provide a custom port. process.env
is just an object defined
in Node's API docs that contains the user
environment. This allows you to define a whole lot of things (including the port
) in which you would
like your process to run. To use it in it's most basic form you could simply include it in your command
line call like this
PORT=8000 node index.js
which will output
'Example app listening on port 8000!'
and run your server on port 8000 as expected. You can also make this a more permanent port by exporting it as an environment variable, thus rendering the need to set it explicitly each time you start up the server unnecessary.
export PORT=8000
node index.js
If you go with this option just keep in mind that you have set an environment variable that will not be explicitly shown to you in your current application. To see an environment variable you can run
echo $PORT
which should output 8000
in our case. To remove this environment variable, you
can run
unset PORT
Now our application will default back to 3000
and we will have to set the port
explicitly in the CLI if we want to change it.
There are limitations to what ports are available for you to run on.
Most of the ports in the thousands are a safe bet, but–at least on Linux
systems–any port below 1024 requires root access. I would recommend against
using any of these ports as they may have consequences later down the road,
but if you must use one of them you can simply prepend sudo
to your command
and enter in your system password (assuming you have root permissions on the
current user on your computer).
sudo PORT=80 node index.js
Let me know if you have questions about any of this :)
how is this command (PORT=8000 node index.js) written to Windows?