简介

Node.js 是一个基于Chrome JavaScript 运行时建设的一个平台。

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

简略的说 Node.js 就是运行在服务端的 JavaScript。

具体学习: 菜鸟教程

一、疾速入门

Hello World

新建js文件 helloworld.js

console.log("hello world!");

终端执行文件(需在文件所在目录下执行)

node helloworld.js
实现繁难HttpServer

新建js文件server.js

var http = require('http');http.createServer(function (request, response) {    // 发送 HTTP 头部     // HTTP 状态值: 200 : OK    // 内容类型: text/plain    response.writeHead(200, {'Content-Type': 'text/plain'});    // 发送响应数据 "Hello World"    response.end('Hello World\n');}).listen(8888);// 终端打印如下信息console.log('Server running at http://127.0.0.1:8888/');

终端执行文件(需在文件所在目录下执行)

node server.js 

敞开nodejs服务

在终端按Ctrl+C

二、NPM包管理器

1. 根本信息

简介,这篇Node.js 包管理器 NPM 解说文章解说具体,点击就可浏览

NPM官方网站

NPM是伴随NodeJS一起装置的包管理工具,能解决NodeJS代码部署上的很多问题,常见的应用场景有以下几种:

  • 容许用户从NPM服务器下载他人编写的第三方包到本地应用。
  • 容许用户从NPM服务器下载并装置他人编写的命令行程序到本地应用。
  • 容许用户将本人编写的包或命令行程序上传到NPM服务器供他人应用。
查看装置

因为新版的nodejs曾经集成了npm,所以之前npm也一并装置好了。能够通过输出 "npm -v" 来测试是否胜利装置,呈现版本提醒示意装置胜利。

$ npm -v2.3.0
npm 降级

Linux零碎环境降级

$ sudo npm install npm -g

Windows零碎环境降级

npm install npm -g

2. 根本利用

2.1 装置模块

npm 装置 Node.js 模块语法格局如下:

$ npm install <Module Name>

以下实例,咱们应用 npm 命令装置罕用的 Node.js web框架模块 express:

$ npm install express

装置好之后,express 包就放在了工程目录下的 node_modules 目录中,因而在代码中只须要通过 require('express') 的形式就好,无需指定第三方包门路。

var express = require('express');

2.2 卸载模块

能够应用以下命令来卸载 Node.js 模块。

$ npm uninstall express

卸载后,能够到 /node_modules/ 目录下查看包是否还存在,或者应用以下命令查看:

$ npm ls

2.3 更新模块

能够应用以下命令更新模块:

$ npm update express

2.4 搜寻模块

能够应用以下来搜寻模块:

$ npm search express

2.5 生成package文件

应用npm疾速生成package.json(相似pom.xml)
npm init //依据提醒作一些设定
{  "name": "nodedemo",//工程名  "version": "1.0.0",//版本号  "description": "npm测试",//形容  "main": "HelloWorld.js",//入口js  "scripts": { //运行脚本    "test": "echo \"Error: no test specified\" && exit 1",    "start": "node server.js"  },  "author": "Hyman",//开发者  "license": "ISC"//受权协定}

三、连贯Mysql

装置mysql模块
npm install mysql
简略样例

新建测试文件MysqlTest.js

var mysql  = require('mysql');  var connection = mysql.createConnection({       host     : 'localhost',         user     : 'root',                password : '123456',         port: '3306',                     database: 'test' }); connection.connect();var  sql = 'SELECT * FROM user';//查(无参写法)connection.query(sql,function (err, result) {        if(err){          console.log('[SELECT ERROR] - ',err.message);          return;        }       console.log('--------------------------SELECT----------------------------');       console.log(result);       console.log('------------------------------------------------------------\n\n');  });var now = new Date();var Sql = 'INSERT INTO user(Id,name,mail,update_date,create_date) VALUES(0,?,?,?,?)';var SqlParams = ['李四', 'lisi@mail.com',now, now];//增(有参写法)connection.query(Sql,SqlParams,function (err, result) {        if(err){         console.log('[INSERT ERROR] - ',err.message);         return;        }               console.log('--------------------------INSERT----------------------------');       //console.log('INSERT ID:',result.insertId);               console.log('INSERT ID:',result);               console.log('-----------------------------------------------------------------');  });connection.end();
注意事项

1、不要把测试文件命名为mysql.js

2、呈现以下谬误

[SELECT ERROR] -  ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgradingMySQL client

谬误起因:最新的mysql模块并未齐全反对MySQL 8的“caching_sha2_password”加密形式,而“caching_sha2_password”在MySQL 8中是默认的加密形式。

解决方案:更改Mysql加密形式

USE mysql;--root为数据库用户,123456为用户对应明码ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';FLUSH PRIVILEGES;

四、编写RESTful API

创立一个 json 数据资源文件 users.json
   "user1" : {      "name" : "mahesh",      "password" : "password1",      "profession" : "teacher",      "id": 1   },   "user2" : {      "name" : "suresh",      "password" : "password2",      "profession" : "librarian",      "id": 2   },   "user3" : {      "name" : "ramesh",      "password" : "password3",      "profession" : "clerk",      "id": 3   }}
创立RESTful API 的文件server.js
var express = require('express');var app = express();var fs = require("fs");//获取用户清单app.get('/listUsers', function (req, res) {   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {       console.log( data );       res.end( data );   });})var user = {    "user4" : {       "name" : "mohit",       "password" : "password4",       "profession" : "teacher",       "id": 4    } } //增加的新用户数据 app.get('/addUser', function (req, res) {    // 读取已存在的数据    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {        data = JSON.parse( data );        data["user4"] = user["user4"];        console.log( data );        res.end( JSON.stringify(data));    }); }) //删除对应用户 app.get('/deleteUser/:id', function (req, res) {    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {        data = JSON.parse( data );        delete data["user" + req.params.id];        console.log( data );        res.end( JSON.stringify(data));    }); })//依据输出id返回后果,须要放在最初,防止烦扰后面的路由app.get('/:id', function (req, res) {fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {    data = JSON.parse( data );    var userTemp = data["user" + req.params.id]     console.log( userTemp );    res.end( JSON.stringify(userTemp));});})var server = app.listen(8081, function () {  var host = server.address().addressnode  var port = server.address().port  console.log("利用实例,拜访地址为 http://%s:%s", host, port)})

接下来执行以下命令

$ node server.js 利用实例,拜访地址为 http://0.0.0.0:8081

在浏览器中拜访 http://127.0.0.1:8081/listUsers

在浏览器中拜访 http://127.0.0.1:8081/addUser

注意事项
  • 如果多个API写在一起,输出型路由应该放在最初

小编建了前端技术交流学习圈,小伙伴们能够问问题料聊技术聊天气聊情绪,点击这期待你的退出!暗号前端。喜爱这篇文章的点赞+评论666反对,没看过小编其余文章的能够看看噢。