NodeJs极速入门扫盲

简介

这里直接引用官网的一句话

Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时。

Node.Js的出现使得后端不再只是Java,PHP,Ruby等语言的天下,使得前端开发人员可以通过他们熟悉的Js来编写后端。

Hello World

一个简单的例子

1
2
3
4
5
6
7
8
9
10
//hello.js

const http = require('http');
//创建http服务
http.createServer(function (request, responce) {
responce.writeHead(200, {'Content-type':'text/plain'});
responce.end('hello server');

}).listen(8080);//监听一个端口
console.log("Server start on 'http://localhost:8080'");

编写好之后执行

1
node hello.js

控制台会输出一句Server start on 'http://localhost:8080',即代表你已经运行成功。

打开浏览器输入上面的url即可看到效果。

数据库操作

首先通过node.js自带的包管理工具npm安装数据库驱动,如MySQL

1
npm install mysql

安装完成后编写代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//db.js

const mysql = require('mysql');

//连接信息
var connection = mysql.createConnection({
host: '{HOST}',
port: 3306,
user: '{USERNAME}',
password: '{PASSWORD}',
database: '{DBNAME}'
});

//创建连接
connection.connect();

//执行sql
connection.query('select * from tb_user', function (error, results) {
if (error) throw error;
console.log('result=', results);
})

//关闭连接
connection.end();

接着在控制台中执行

1
node db.js

就可以在控制台中看到效果

待更新…