Skip to content

Instantly share code, notes, and snippets.

@sandrabosk
Last active April 30, 2020 02:18
Show Gist options
  • Save sandrabosk/1881265ae15dddd532480f42a6354e30 to your computer and use it in GitHub Desktop.
Save sandrabosk/1881265ae15dddd532480f42a6354e30 to your computer and use it in GitHub Desktop.

Simple Node HTTP Server - demo

  1. Set up:
$ mkdir node-http-server
$ cd node-http-server
$ npm init --yes
$ npm i dotenv 
$ touch server.js secret.js

Your folder/file tree should look like this:

.
├── package-lock.json
├── package.json
├── node_modules
├── secret.js
└── server.js
  1. Use code from the server.js to explain how to create and use our first server.

  2. To run:

$ node server.js

💡 Remember to CONTROL + C to stop the previous version of the server and run it again with node server.js.

PORT = 3000
// run node server.js in terminal and BOOM!
console.log('Is this my first node project? ☝🏻');
// all requires will always go in the beginning of the file!
// how to get package in this file (require)...
const myHttp = require('http');
require('dotenv').config();
// how to create server (and use packages):
const myServer = myHttp.createServer((request, response) => {
console.log(`Requested URL is: ${request.url}`);
if (request.url === '/') {
response.write('You requested localhost:3000 my friend!');
response.end();
} else if (request.url === '/ptwd102019') {
response.write(`
Kevin
Vero
Ashraf
Jerlissa
`);
response.end();
} else {
response.write(
`You are trying to access the page that does not exist! Error: 404`
);
response.end();
}
});
// myServer.listen(3000, () => console.log('I am 🏃‍♂️ on port 3000!'));
myServer.listen(process.env.PORT, () => console.log('I am 🏃‍♂️ on port 3000!'));
# env varibles don't go to github but for learning purposes we might sometimes push them
# .env
node_modules
secret.js # this file won't be pushed to GitHub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment