Difference between revisions of "Node.js - Express.js"

From Sinfronteras
Jump to: navigation, search
(Creating and Compiling a new TypeScript project)
(Creating a new TypeScript Node.js project)
Line 230: Line 230:
 
Example app listening on port 3000!
 
Example app listening on port 3000!
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
 +
You can then open Google Chrome and visit http://localhost:3030 and if everything went well you should see the following on the screen:
 +
<syntaxhighlight lang="bash">
 +
Hello World!
 +
</syntaxhighlight>
 +
 +
Once the server is running you cannot use the bash anymore unless you kill the process. You can kill the process by pressing Ctrl + c when focus on the bash.
 +
 +
<span style="color:#FF0000">Please note that if you change the code you will need to save the changes, kill the process using Ctrl + c and run it again with ts-node. Later in this document, we will learn a way to automatically re-load the server when the code changes but it is important to know how to do it by hand.</span>
  
 
==Compilation==
 
==Compilation==

Revision as of 21:43, 14 November 2018

Curso online que Remo recomendó:

https://javascript30.com/

https://courses.wesbos.com/account/access/5bc5c20a93bbc3208321f21b

TypeScript

TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language.

TypeScript is designed for development of large applications and transcompiles to JavaScript. As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs. TypeScript may be used to develop JavaScript applications for both client-side and server-side.

To get started with TypeScript installation, you need to first install Node.js in your system.

Node.js

Install Node.js https://nodejs.org/en/download/ https://en.wikipedia.org/wiki/Node.js

Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser. Historically, JavaScript was used primarily for client-side scripting, in which scripts written in JavaScript are embedded in a webpage's HTML and run client-side by a JavaScript engine in the user's web browser. Node.js lets developers use JavaScript to write Command Line tools and for server-side scripting-running scripts server-side to produce dynamic web page content before the page is sent to the user's web browser. Consequently, Node.js represents a "JavaScript everywhere" paradigm, unifying web application development around a single programming language, rather than different languages for server side and client side scripts.

Installation

https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions

curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs


Alternatively, for Node.js 10:

curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs


You can check that Node.js was installed correctly by executing the following command in Bash:

node -v


Node package manager - npm

The Node.js installer will install the node command in your machine but it will also install the Node package manager (npm) command. You can also test that npm has been installed correctly by executing the following command:

npm -v

We can use the npm command to install third-party Node.js packages. The npm command allows us to install a few different kinds of dependencies:

  • Global dependencies (shared across projects)
  • Dependencies (local, not shared across projects and needed during the execution of the application, or in other words after development)
  • Development dependencies (local, not shared across the project and needed only during development)


We can install npm dependencies using the following commands:

  • Install a global dependency:
npm install -g NAME_OF_THE_DEPENDENCY
  • Install a local dependency:
npm install --save NAME_OF_THE_DEPENDENCY
  • Install a local development dependency:
npm install --save-dev NAME_OF_THE_DEPENDENCY

You can learn more about npm by reading the official documentation at https://docs.npmjs.com

Installing TypeScript and ts-node

TypeScript and ts-node can be installed using the Node Package Manager (NPM). We will install them as global dependencies:

npm install -g typescript
npm install -g ts-node

Because we have installed both dependencies as global dependencies these will be shared across all projects in our computer. This means that we only need to run these commands once.

You can learn more about npm by reading the official documentation at https://docs.npmjs.com


After installingTypeScript, the command tsc should become available:

tsc -v

Also:

ts-node -v

Git Bash in Windows

Si estamos en Windows, tenemos que instalar Git Bash in Windows; que es tan sólo un terminal Bash en Windows.

Visual Studio Code

https://code.visualstudio.com/download/

https://en.wikipedia.org/wiki/Visual_Studio_Code

Visual Studio Code is a source code editor developed by Microsoft for Windows, Linux and macOS. It includes support for debugging, embedded Git control, syntax highlighting, intelligent code completion, snippets, and code refactoring.

Installation

Download the <file>.deb: https://code.visualstudio.com/download Installation: https://code.visualstudio.com/docs/setup/linux

Creating and Compiling a new TypeScript project

Creating a new TypeScript project

Each new TypeScript project requires a new empty folder. It is recommended to create a new folder under your home directory. I call this directory "CODE" and inside it, I create a new empty folder for each project.

A TypeScript project could be a Node.js project but it could also not be a Node.js project. For example, it could be an Angular or React.js project. In this section, we are going to focus on the steps required to create a TypeScript project independently of the kind of application that we will build.

All our TypeScript projects are going to need the following:

1- A new empty directory
2- A TypeScript compiler configuration file (tsconfig.json)
tsc --init
3- An npm configuration file (package.json)
npm init --y
4- At this point, we are ready to open the project using VS Code. To open a project in VS Code we need to open VS Code and select File → Open Folder...
5- After opening the folder in VS Code, we need to create a new folder. This time we will use the VS Code feature that allows us to create a new folder. I’m going to name the folder src.
6- Then I will create a new file named demo.ts using VS Code. The file will be contained inside the src directory.
7- Finally, I will add some content to the demo.ts file. In this case, we are going to add just one line of code:
console.log("Hello world!");
VisualStudio TypeScript project.png

You will need to repeat these steps everytime you create a new TypeScript project. It is very important to use a new empty folder to avoid potential configuration issues.

Compiling and running a TypeScript project

Now that we have created the basic structure of a TypeScript project we are going to compile it and execute it. To compile the TypeScript project we need to use the tsc command and the project flag to specify the TypeScript compiler configuration file:

tsc -p tsconfig.json


If everything goes well this will generate a new file named demo.js right next to the existing demo.ts file. We can then execute the JavaScript file demo.js using the node command:

node ./src/demo.js


Please note that the node command can only be used to execute JavaScript files (.js) not TypeScript files (.ts) this means that we must compile our application before we can run it. This requires two steps and it is a bit tedious. However, we can use the ts-node command to do the two steps with one single command:

ts-node ./src/demo.ts

Note that the ts-node command can be used with TypeScript files.

Creating a new TypeScript Node.js project

If we are going to work on a Node.js application we are going to need a few additional steps. First, we need to install the Node.js type definitions. We can do this using npm:

npm install --save-dev @types/node


We are also going to open the tsconfig.json and uncomment the "lib" setting and add the following value:

"lib": [ "es6" ]


At this point, we should be able to import the Node.js core modules. For example, we can import the file system module as follows:

import * as fs from "fs";

Working with dependencies

Sometimes we will need additional npm modules like for example Express. The npm modules sometimes a compatible with TypeScript automatically. Other times, we need to install additional npm module that contains the type definitions that allow us to use the module in TypeScript. In the case of Express, we need to install the express module and the @types/express module:

npm install --save express
npm install --save-dev @types/express

We can then import express as follows:

import express from "express";

This will fail if you forget to install both modules.

Running an Express application

At this point, we should be able to create a very basic Express application and execute it to see if everything has gone right so far. We are going to change the content of the demo.ts file from:

console.log("Hello world!");

To:

import express from "express";

const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'));

app.listen(
  port,
  () => console.log(`Example app listening on port ${port}!`)
);


We can then the run the Express application using:

ts-node ./src/demo.ts


If everything goes well the following should be displayed in bash:

Example app listening on port 3000!


You can then open Google Chrome and visit http://localhost:3030 and if everything went well you should see the following on the screen:

Hello World!

Once the server is running you cannot use the bash anymore unless you kill the process. You can kill the process by pressing Ctrl + c when focus on the bash.

Please note that if you change the code you will need to save the changes, kill the process using Ctrl + c and run it again with ts-node. Later in this document, we will learn a way to automatically re-load the server when the code changes but it is important to know how to do it by hand.

Compilation

Para preparar el directorio, primero hay que ejecutar:

tsc --init
npm init
npm init --y  (podemos ejecutarlo así para responder (yes) automáticamente a las preguntas.

Luego:

npm install @types/node


npm install jquery
tsc -p tsconfig.json
node demo.js
ts-node demo.ts