Node.js Project 1: Set up a Simple Web Server
Basic Setup
Description:
- Install MEAN in AWS Lightsail
- Configure Node.js
- Code HTML/Bootstrap
Hosting:
- Create AWS Account
- Create AWS Lightsail Instance with Bitnami MEAN image
Node.js Configuration:
Node.js has been installed after the creation of the Lightsail Instance.
To configure the Node.js, connect to the AWS Lightsail Instance via SSH. To initiate a project, you can execute the following command:
$ express --view pug ~/projects/sample
$ cd ~/projects/sample
$ npm install
$ DEBUG=sample:* npm start
> [email protected] start /opt/bitnami/projects/sample
> node ./bin/www
sample:server Listening on port 3000 +0ms
The Node.js server listen to the network port 3000 of the host. However, we commonly use https (port 443) or http (port 80) to serve the browser. Therefore, we have to setup the webserver to “tunnel” the port 443 to port 3000.
$ cd /home/bitnami/stack/apache2/conf/vhosts
$ cp sample-https-vhost.conf.disabled sample-https-vhost.conf
After configure the Apache webserver, we have to restart it.
sudo /opt/bitnami/ctlscript.sh restart apache
If you have killed the Node.js process, you have to go to the sample project directory and re-initiate the Node.js server.
$ cd ~/projects/sample
$ DEBUG=sample:* npm start
> [email protected] start /opt/bitnami/projects/sample
> node ./bin/www
sample:server Listening on port 3000 +0ms
You can now start a browser and go to the web server by https://<your-server-ip-address>.
To start the Node.js server in background, you can use the following command:
npm start > log.txt &
Advanced Knowledge
What is “npm start”?
4 common shorthands of npm script:
npm start = npm run start
npm stop = npm run stop
npm test = npm run test
npm restart = npm run stop && npm run restart && npm run start
When we execute npm run <command>, it will look for the script written in package.json file in the project root.
The content of the package.json file:
{
// ...
"scripts": {
"start": "node ./bin/www"
}
}
If we execute npm run start, it will execute node ./bin/www .
How does npm script work?
When we execute npm run, a new Shell will be created. The script will be executed under the new Shell. Therefore, we can write any bash script in npm script.
The new Shell will also add the node_modules/.bin folder into PATH variables and remove the PATH variable after execution. With this effect, the scripts under node_modules/.bin directory can be executed directly without the full path. For example, if there is a project dependency “Mocha”, we can write mocha test.
“test”: “mocha test”
rather than
“test”: “./node_modules/.bin/mocha test”
There is only a requirement for npm script, that is we have to run the script in Shell. So, the npm script can be any executables other than node script.
npm script exit code follows Shell script. If the exit code is not 0, npm will determine the execution is failed.