Installing NodeJS on Linux
FIrst step: install node on your server, the node package manager is already included (npm)
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt install -y nodejs
Install yarn package manager - caches downloads
sudo apt install yarn
Node installed, let's head over to build our first web server!
Inside an app.js file:
// node server config
const http = require('http');
// localhost - IP loopback connection to my machine - for now
// since I don't have port forwarding setup yet
const hostname = '127.0.0.1';
// default port for NodeJS: 3000
const port = '3000';
// http.createServer([options][, requestListener]
// requestListener is a function
// return an instance of http.server
const server = http.createServer((req, res) => {
// HTTP status code 200 = OK
res.statusCode = 200;
// setting the HTML header - metadata
res.setHeader('Content-Type', 'text/plain');
// signal that all response headers have been sent
// can include data, encoding or a callback
// this method MUST be called in each response
res.end("yoOOooOoOOoOoOOOoOOo");
});
server.listen(port, hostname, () => {
console.log(`Your awesome server is running at http://${hostname}:${port}/`);
});
Our Node server is up and running on localhost!
Further we will learn how to link it to a database and various frameworks / apps.
Komentáře
Okomentovat