Node.js的安装和基础使用

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的速度非常快,性能非常好。

下载

安装

默认安装即可
安装完成后在cmd运行 node -v 命令查看是否安装成功
在这里插入图片描述

Nodejs入门

快速入门-Hello World

创建 helloworld.js文件

//类似于java中的System.out.println("")
console.log('Hello World!!!')

在这里插入图片描述
在终端输入node helloworld.js命令,运行helloworld.js (ctrl+` 打开终端)

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

在这里插入图片描述

Node - 实现请求响应

查看帮助文档中Node.js内置http,可以直接使用
1、创建 httpserver.js ;

// 导入模块是require 就类似于import java.io 
const http = require('http');
// 1: 创建一个httpserver服务
http.createServer(function(request,response){
    
    
    // 浏览器怎么认识hello server!!! 
    response.writeHead(200,{
    
    'Content-type':'text/plain'}); //这句话的含义是:告诉浏览器将以text-plain(文本)去解析hello server 这段数据。
    //response.writeHead(200,{'Content-type':'text/html'}); //这句话的含义是:告诉浏览器将以text-html去解析hello server 这段数据。
    // 给浏览器输出内容
    // 给浏览器输出内容
    response.end("<strong>hello server!!!</strong>");
}).listen(8888);// 2: 监听一端口8888
console.log("你启动的服务是:http://localhpst:8888以启动成功!!");
// 3: 终端启动运行服务 node httpserver.js
// 4: 在浏览器访问http://localhost:8888

2、运行服务器程序;在浏览器访问http://localhost:8888

node httpserver.js

在这里插入图片描述
在这里插入图片描述
3. 终端停止服务:ctrl + c

Node-操作MYSQL数据库

Node.js没有内置MySQL
1:安装mysql依赖
在终端运行npm install mysql
在这里插入图片描述
2:创建db.js进行数据库操作

//1: 导入mysql依赖包,  mysql属于第三方的模块就类似于 java.sql一样的道理
var mysql = require("mysql");
// 1: 创建一个mysql的Connection对象
// 2: 配置数据连接的信息 
var connection =mysql.createConnection({
    
    
    host:"127.0.0.1",
    port:3306,
    user:"root",
    password:"root",
    database:"mybatis-plus"
});
// 3:开辟连接
connection.connect();
// 4: 执行curd
connection.query("select * from user",function(error,results,fields){
    
    
    // 如果查询出错,直接抛出
    if(error)throw error;
    // 查询成功
    console.log("results = ",results);
});
// 5: 关闭连接
connection.end();
// 最后一步:运行node db.js 查看效果

3. 运行db.js

node db.js

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44058265/article/details/120616418