Introducció
Nodejs
Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project!
Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant.
A Node.js app runs in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.
nvm
nvm is a popular way to run Node.js. It allows you to easily switch the Node.js version, and install new versions to try and easily rollback if something breaks. It is also very useful to test your code with old Node.js versions.
To install or update nvm, you should run the install script. To do that, you may either download and run the script manually, or use the following cURL or Wget command:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh | bash
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh | bash
Running either of the above commands downloads a script and runs it. The script clones the nvm repository to ~/.nvm, and updates the ~/.bashrc profile file.
Important!. Close and reopen your terminal to start using nvm
Usage
To download, compile, and install the latest release of node, do this:
nvm install node # "node" is an alias for the latest version
To install a specific version of node:
nvm install 14.7.0 # or 16.3.0, 12.22.1, etc
The first version installed becomes the default. New shells will start with the default version of node (e.g., nvm alias default).
You can list available versions using ls-remote:
nvm ls-remote
And then in any new shell just use the installed version:
nvm use node
Or you can just run it:
nvm run node --version
Web Server
Once we have installed Node.js, let's build our first web server. Create a file named app.js containing the following contents:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Now, run your web server:
node app.js
Visit http://localhost:3000 and you will see a message saying "Hello World".
curl http://localhost:3000