Chạy NodeJS trên Visual code

Khi học lập trình Node JS thì các bạn có thể sử dụng IDE hoặc Editor. Nếu sử dụng IDE thì bạn có thể sử dụng IDE tốt nhất cho Node chính là Webstorm của JetBrains, tuy nhiên công cụ này là trả phí và giá khá là cao nên mình không khuyến khích sử dụng nếu bạn là sinh viên hoặc là người mới nghiên cứu về Node JS. Bạn có thể tài bản dùng thử 30 ngày của Webstorm nếu muốn thử trả nghiệm.

Cá nhân mình thì rất thích và đang sử dụng Atom của Github với một cộng đồng lớn mạnh hỗ trợ và hoàn toàn miễn phí. Ngoài ra còn có một công cụ khác miễn phí nữa chính là Visual Studio Code của Microsoft, đây cũng là công cụ rất được ưa thích. Và Editor cuối mình giới thiệu chính là Sublime Text , không cần nói nhiều đây là công cụ được ưa thích từ rất lâu, tuy nhiên theo đánh giá của cá nhân mình thì thứ nhất nó không hoàn toàn miễn phí, thứ hai các plugin hỗ trợ không đa dạng bằng Atom hoặc Visual Studio Code.

Vậy tóm lại các bạn sẽ cài 1 trong 3 Editor dưới đây để thực hành nhé.

1. Atom : https://atom.io/

2. Visual Studio Code : https://code.visualstudio.com/

3. Sublime Text : https://www.sublimetext.com/

 

III. Chạy thử ứng dụng đầu tiên.

Để làm được việc này các bạn chắc chắn phải cài được Node JS và NPM trên máy tính, có thể xem lại bài hướng dẫn cài đặt nếu các bạn chưa làm được bước này.

 

Bước 1. Khởi tạo Project .

Đầu tiên các bạn tạo thư mục có tên là helloworld-nodejs ở đâu đó trên máy tính và vào thử mục đó mở Terminal lên (CMD với Windowns) và gõ vào lệnh sau.

npm init

Sau đó thì nó sẽ yêu cầu các bạn nhập thông tin cho Project mới, các bạn cứ nhập theo hướng dẫn là được, ví dụ như mình nhập bên dưới .

 

 

name: (nodejs) sociss-class-nodejs

version: (1.0.0)

description: Base project for teaching and learing.

entry point: (index.js)

test command: npm test

git repository:

keywords: sociss class, sociss education, sociss nodejs

author: Nguyen Huu Quyen

license: (ISC) MIT

Sau khi kết thúc bước này các bạn sẽ thấy nó tạo ra một file tên là package.json

Đây chính là file chứa thông tin cài đặt của Project, về sau toàn bộ thông tin các bộ thư viện hoặc các đoạn Script cho ứng dụng đều được khai báo ở đây.

Mình sẽ có một chương nói cụ thể hơn về NPM trong khóa học này .

Bước 2. Cài đặt thư viện cần thiết cho Project.

 Từ Terminal các bạn chạy lệnh sau .

 

npm install

Lúc này NPM sẽ truy cập mạng và tải toàn bộ các bộ thư viện cần thiết về, nếu không có kết nối mạng, quá trình trên sẽ thấy bại. Bạn có thể phải chờ khá lâu nếu mạng chậm, máy tính mình thì cần tầm 5 phút là xong .

Nếu các bạn bị lỗi : npm WARN [email protected] No repository field.

Thì chỉ cần mở file package.json lên và sửa thêm vào một dòng repository như dưới đây.

{
  "name": "sociss-class-nodejs",
  "version": "1.0.0",
  "description": "Base project for teaching and learing.",
  "main": "index.js",
  "scripts": {
    "test": "npm test"
  },
  "repository" : "https://github.com/nghuuquyen/sociss-class-nodejs.git",
  "keywords": [
    "sociss",
    "class",
    "sociss",
    "education",
    "sociss",
    "nodejs"
  ],
  "author": "Nguyen Huu Quyen",
  "license": "MIT"
}

Nếu không có Remote Git thì bạn cứ tạm điền vào đó là NONE cũng được, mình sẽ bày các tạo GIT project sau.

Sau đó mở Editor lên tạo một file index.js ở thư mục gốc rồi gõ vào đó đoạn code sau .

console.log('Hello World.');

Cuối cùng tại Terminal chạy lệnh

node index

Nếu màn hình in ra dòng Hello World thì là đã thành công nhé . Tới đây là bạn đã xong bài tập đầu tiên rồi.

Node.js is a platform for building fast and scalable server applications using JavaScript. Node.js is the runtime and npm is the Package Manager for Node.js modules.

Visual Studio Code has support for the JavaScript and TypeScript languages out-of-the-box as well as Node.js debugging. However, to run a Node.js application, you will need to install the Node.js runtime on your machine.

To get started in this walkthrough, install Node.js for your platform. The Node Package Manager is included in the Node.js distribution. You'll need to open a new terminal (command prompt) for the node and

var msg = 'Hello World';
console.log(msg);
0 command-line tools to be on your PATH.

To test that you have Node.js installed correctly on your computer, open a new terminal and type

var msg = 'Hello World';
console.log(msg);
1 and you should see the current Node.js version installed.

Linux: There are specific Node.js packages available for the various flavors of Linux. See Installing Node.js via package manager to find the Node.js package and installation instructions tailored to your version of Linux.

Windows Subsystem for Linux: If you are on Windows, WSL is a great way to do Node.js development. You can run Linux distributions on Windows and install Node.js into the Linux environment. When coupled with the WSL extension, you get full VS Code editing and debugging support while running in the context of WSL. To learn more, go to Developing in WSL or try the Working in WSL tutorial.

Hello World

Let's get started by creating the simplest Node.js application, "Hello World".

Create an empty folder called "hello", navigate into and open VS Code:

mkdir hello
cd hello
code .

Tip: You can open files or folders directly from the command line. The period '.' refers to the current folder, therefore VS Code will start and open the

var msg = 'Hello World';
console.log(msg);
2 folder.

From the File Explorer toolbar, press the New File button:

Chạy NodeJS trên Visual code

and name the file

var msg = 'Hello World';
console.log(msg);
3:

Chạy NodeJS trên Visual code

By using the

var msg = 'Hello World';
console.log(msg);
4 file extension, VS Code interprets this file as JavaScript and will evaluate the contents with the JavaScript language service. Refer to the VS Code JavaScript language topic to learn more about JavaScript support.

Create a simple string variable in

var msg = 'Hello World';
console.log(msg);
3 and send the contents of the string to the console:

var msg = 'Hello World';
console.log(msg);

Note that when you typed

var msg = 'Hello World';
console.log(msg);
6 IntelliSense on the
var msg = 'Hello World';
console.log(msg);
7 object was automatically presented to you.

Chạy NodeJS trên Visual code

Also notice that VS Code knows that

var msg = 'Hello World';
console.log(msg);
8 is a string based on the initialization to
var msg = 'Hello World';
console.log(msg);
9. If you type
node app.js
0 you'll see IntelliSense showing all of the string functions available on
var msg = 'Hello World';
console.log(msg);
8.

Chạy NodeJS trên Visual code

After experimenting with IntelliSense, revert any extra changes from the source code example above and save the file (⌘S (Windows, Linux Ctrl+S)).

Running Hello World

It's simple to run

var msg = 'Hello World';
console.log(msg);
3 with Node.js. From a terminal, just type:

node app.js

You should see "Hello World" output to the terminal and then Node.js returns.

Integrated Terminal

VS Code has an integrated terminal which you can use to run shell commands. You can run Node.js directly from there and avoid switching out of VS Code while running command-line tools.

View > Terminal (⌃` (Windows, Linux Ctrl+`) with the backtick character) will open the integrated terminal and you can run

node app.js
3 there:

Chạy NodeJS trên Visual code

For this walkthrough, you can use either an external terminal or the VS Code integrated terminal for running the command-line tools.

Debugging Hello World

As mentioned in the introduction, VS Code ships with a debugger for Node.js applications. Let's try debugging our simple Hello World application.

To set a breakpoint in

var msg = 'Hello World';
console.log(msg);
3, put the editor cursor on the first line and press F9 or click in the editor left gutter next to the line numbers. A red circle will appear in the gutter.

Chạy NodeJS trên Visual code

To start debugging, select the Run and Debug view in the Activity Bar:

Chạy NodeJS trên Visual code

You can now click Debug toolbar green arrow or press F5 to launch and debug "Hello World". Your breakpoint will be hit and you can view and step through the simple application. Notice that VS Code displays a different colored Status Bar to indicate it is in Debug mode and the DEBUG CONSOLE is displayed.

Chạy NodeJS trên Visual code

Now that you've seen VS Code in action with "Hello World", the next section shows using VS Code with a full-stack Node.js web app.

Note: We're done with the "Hello World" example so navigate out of that folder before you create an Express app. You can delete the "Hello" folder if you want as it is not required for the rest of the walkthrough.

An Express application

Express is a very popular application framework for building and running Node.js applications. You can scaffold (create) a new Express application using the Express Generator tool. The Express Generator is shipped as an npm module and installed by using the npm command-line tool

var msg = 'Hello World';
console.log(msg);
0.

Tip: To test that you've got

var msg = 'Hello World';
console.log(msg);
0 correctly installed on your computer, type
node app.js
7 from a terminal and you should see the usage documentation.

Install the Express Generator by running the following from a terminal:

npm install -g express-generator

The

node app.js
8 switch installs the Express Generator globally on your machine so you can run it from anywhere.

We can now scaffold a new Express application called

node app.js
9 by running:

express myExpressApp --view pug

This creates a new folder called

node app.js
9 with the contents of your application. The
npm install -g express-generator
1 parameters tell the generator to use the pug template engine.

To install all of the application's dependencies (again shipped as npm modules), go to the new folder and execute

npm install -g express-generator
2:

cd myExpressApp
npm install

At this point, we should test that our application runs. The generated Express application has a

npm install -g express-generator
3 file which includes a
npm install -g express-generator
4 script to run
npm install -g express-generator
5. This will start the Node.js application running.

From a terminal in the Express application folder, run:

npm start

The Node.js web server will start and you can browse to http://localhost:3000 to see the running application.

Chạy NodeJS trên Visual code

Great code editing

Close the browser and from a terminal in the

node app.js
9 folder, stop the Node.js server by pressing CTRL+C.

Now launch VS Code:

code .

Note: If you've been using the VS Code integrated terminal to install the Express generator and scaffold the app, you can open the

node app.js
9 folder from your running VS Code instance with the File > Open Folder command.

The Node.js and Express documentation does a great job explaining how to build rich applications using the platform and framework. Visual Studio Code will make you more productive in developing these types of applications by providing great code editing and navigation experiences.

Open the file

var msg = 'Hello World';
console.log(msg);
3 and hover over the Node.js global object
npm install -g express-generator
9. Notice how VS Code understands that
npm install -g express-generator
9 is a string. Even more interesting, you can get full IntelliSense against the Node.js framework. For example, you can require
express myExpressApp --view pug
1 and get full IntelliSense against the
express myExpressApp --view pug
1 class as you type in Visual Studio Code.

Chạy NodeJS trên Visual code

VS Code uses TypeScript type declaration (typings) files (for example

express myExpressApp --view pug
3) to provide metadata to VS Code about the JavaScript based frameworks you are consuming in your application. Type declaration files are written in TypeScript so they can express the data types of parameters and functions, allowing VS Code to provide a rich IntelliSense experience. Thanks to a feature called
express myExpressApp --view pug
4, you do not have to worry about downloading these type declaration files, VS Code will install them automatically for you.

You can also write code that references modules in other files. For example, in

var msg = 'Hello World';
console.log(msg);
3 we require the
express myExpressApp --view pug
6 module, which exports an
express myExpressApp --view pug
7 class. If you bring up IntelliSense on
express myExpressApp --view pug
8, you can see the shape of the
express myExpressApp --view pug
9 class.

Chạy NodeJS trên Visual code

Debug your Express app

You will need to create a debugger configuration file

cd myExpressApp
npm install
0 for your Express application. Click on Run and Debug in the Activity Bar (⇧⌘D (Windows, Linux Ctrl+Shift+D)) and then select the create a launch.json file link to create a default
cd myExpressApp
npm install
0 file. Select the Node.js environment by ensuring that the
cd myExpressApp
npm install
2 property in
cd myExpressApp
npm install
3 is set to
cd myExpressApp
npm install
4. When the file is first created, VS Code will look in
npm install -g express-generator
3 for a
npm install -g express-generator
4 script and will use that value as the
cd myExpressApp
npm install
7 (which in this case is
cd myExpressApp
npm install
8) for the Launch Program configuration.

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${workspaceFolder}\\bin\\www"
    }
  ]
}

Save the new file and make sure Launch Program is selected in the configuration dropdown at the top of the Run and Debug view. Open

var msg = 'Hello World';
console.log(msg);
3 and set a breakpoint near the top of the file where the Express app object is created by clicking in the gutter to the left of the line number. Press F5 to start debugging the application. VS Code will start the server in a new terminal and hit the breakpoint we set. From there you can inspect variables, create watches, and step through your code.

Chạy NodeJS trên Visual code

Deploy your application

If you'd like to learn how to deploy your web application, check out the Deploying Applications to Azure tutorials where we show how to run your website in Azure.