020_Nodejs


简介

Node 是一个让 JavaScript 运行在服务端的开发平台,它让 JavaScript 成为与PHP、Python、Perl、Ruby 等服务端语言平起平坐的脚本语言。  发布于2009年5月,由Ryan Dahl开发,实质是对Chrome V8引擎进行了封装。

简单的说 Node.js 就是运行在服务端的 JavaScript。 Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台。底层架构是:javascript. 文件后缀:.js

Node.js是一个事件驱动I/O服务端JavaScript环境,基于Google的V8引擎,V8引擎执行Javascript的速度非常快,性能非常好。

Nodejs是一门计算机语言,运行在系统中的v8(jvm)引擎中。文件后缀是 js 运行的命令是:node


下载安装Nodejs

下载Nodejs

地址:http://nodejs.cn/download/current/
注:选择LTS版本,即长期支持版
image.png
image.png

安装Nodejs报错及解决

参考文档:https://blog.csdn.net/xinxiaoyonng/article/details/109689394
image.png
报错:This application is only supported on Windows 8.1, Windows Server 2012 R2, or higher
原因:当前所安装的nodeJs版本相对于不在维护的windows7系统来说,版本太高了。在v12.16.2以上版本就不在支持window7系统。
解决方法:下载并安装 nodejs v12.16.2及之前的版本即可(降级安装)。

下载nodejs v12.16.2

地址:https://nodejs.org/zh-cn/download/releases/
image.png
image.png
image.png

安装Nodejs v12.16.2

image.png
image.png
image.png
image.png
image.png
image.png
image.png
注:安装完成后会自动弹窗,可以关闭
image.png

测试是否安装成功

# 查询版本号
node -v

npm -v

image.png

Nodejs第一个程序

新建目录nodejs

image.png

打开vscode,打开目录nodejs

image.png

创建文件helloworld.js

image.png

打开终端

image.png

编写代码,执行程序

image.png

运行命令:node

node helloworld.js

浏览器的内核包括两部分

DOM渲染引擎

JavaScript解析器(JS引擎)

JS运行在浏览器内核中的JS引擎内部

Nodejs是脱离浏览器环境运行的JavaScript程序,基于V8引擎

Nodejs帮助文档

Nodejs中文网:http://nodejs.cn/
Nodejs中文网API文档:http://nodejs.cn/api/
image.png

Node实现请求响应

httpAPI文档

地址:http://nodejs.cn/api/http.html
image.png

创建httpserver.js

image.png

编写代码

// 导入模块使用require 相当于java的import导包
const http = require('http');

// 1.创建一个httpserver服务
http.createServer(function(request,response){
    // 告诉浏览器以什么方式解析输出的数据
    response.writeHead(200,{'Content-type':'text/plain'});
    // 给浏览器输出内容
    response.end("<strong>hello server!!!</strong>")
}).listen(8888);
console.log("你启动的服务是:http://localhost:8888,以启动成功!");
// 2.监听端口8888
// 3.启动运行服务 node httpserver.js
// 4.在浏览器访问http://localhost:8888

运行程序

node httpserver.js

image.png

浏览器访问

image.png

停止服务:Ctrl+c

image.png
image.png

Node操作MySQL数据库

安装mysql依赖

参考:https://www.npmjs.com/package/mysql

npm install mysql

image.png
注:安装成功后,出现node_modules目录

编写db.js

// 导入mysql依赖包,mysql属于第三方模块
var mysql = require("mysql");

// 1.创建一个mysql的connection对象
// 2.配置数据连接的信息
var connection = mysql.createConnection({
    host:"127.0.0.1",
    port:3306,
    user:"root",
    password:"123456",
    database:"ssm"
});
// 3.开辟连接
connection.connect();
// 4.执行curd
connection.query("select * from books where book_id=1",function(error,results,fields){
    // 如果查询出错,直接抛出
    if(error)throw error;
    // 查询成功
    console.log("results = ",results);
});
// 5.关闭连接
connection.end();
// 6.运行,node db.js 或 node db,查看结果

image.png

posted @ 2021-10-10 12:00  清风(学习-踏实)  阅读(33)  评论(0编辑  收藏  举报