Nodejs

Author Avatar
kevin
发表:2020-06-22 15:47:00
修改:2024-10-09 15:47:36

创建前端工程必须先cnpm init -y初始化

node不支持es6,需要babel转码

Node.js 就是运行在服务端的 JavaScript

官网:https://nodejs.org/en/

中文网:http://nodejs.cn/

当前使用版本

v10.14.2

快速入门

创建文件

server.js

//引入模块
const 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 Server');
}).listen(8888);  //监听端口
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

cmd运行服务器程序

node server.js

浏览器访问http://localhost:8888/

模块化

exports出口模块

所谓的模块,就是别人写的 js

每个文件就是一个模块,有自己的作用域。在一个文件里面定义的变量、函数、类,都是私有的,对其他文件不可见。

es5写法

写模块

函数少可以单个导出(exports)

function service(request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello Node.js');
}
function sayHello(){
    console.log('hello from how2j.js');
}
//允许外部通过 hi() 这个函数名称调用 sayHello() 这个函数
exports.hi = sayHello;
//允许外部通过 service() 同名调用
exports.service = service;

函数多个情况,使用model多个导出(exports)

// 定义成员:
const sum = function(a,b){
    return parseInt(a) + parseInt(b)
}
const subtract = function(a,b){
    return parseInt(a) - parseInt(b)
}
const multiply = function(a,b){
    return parseInt(a) * parseInt(b)
}
const divide = function(a,b){
    return parseInt(a) / parseInt(b)
}
// 导出成员:
//同名省略
module.exports = {
    sum,
    subtract,
    multiply,
    divide
}

导入模块

require引入模块

记得,加上 ./ 当前目录,否则会到 node安装目录下去寻找 ,除非全局安装

var http = require('http');
var how2j = require('./how2j');
how2j.hi();
var server = http.createServer(how2j.service);
server.listen(8088);

或者

//引入模块,注意:当前路径必须写 ./
const m = require('./四则运算.js')
//console.log(m)
const result1 = m.sum(1, 2)
const result2 = m.subtract(1, 2)
console.log(result1, result2)

es6写法(常用)

写模块

export default {
    getList() {
        console.log('获取数据列表2')
    },

    save() {
        console.log('保存数据2')
    }
}

导入模块

//只取需要的方法即可,多个方法用逗号分隔
import user from "./xxxx.js"  //当前文件加./
getList()  //调用函数
save()    //调用函数

这时的程序无法运行的,因为ES6的模块化无法在Node.js中执行,需要用Babel编辑成ES5后再执行。

需要转码器

安装

npm install --global babel-cli

创建配置文件 .babelrc

 {
     //presets字段设定转码规则
    "presets": ["es2015"],
    "plugins": []
}

安装转码器

npm install --save-dev babel-preset-es2015

转码

# 转码结果写入一个文件
mkdir dist1
# --out-file 或 -o 参数指定输出文件
babel src/example.js --out-file dist1/compiled.js
# 或者
babel src/example.js -o dist1/compiled.js

# 整个目录转码
mkdir dist2
# --out-dir 或 -d 参数指定输出目录
babel src --out-dir dist2
# 或者
babel src -d dist2

npm

Node.js的包管理工具,相当于前端的Maven

发布模块

注册 https://www.npmjs.com/ 激活邮箱

npm init创建package.json 文件,用来告诉 npmjs.com 这个模块的相关信息。

{
    //项目名称
  "name": "yeejava", 
    //项目版本号
  "version": "1.0.0",
    //项目描述
  "description": "npm of yeejava",
    //主方法
  "main": "test.js",
    //默认
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
    //关键词,便于用户搜索到我们的项目
  "keywords": [
    "yee"
  ],
    //作者
  "author": "yee",
    //默认
  "license": "ISC"
}

在发布之前用如下命令登陆

npm adduser

填写账户名(不是邮箱)和密码

成功登陆之后,就可以发布模板了

npm publish

安装模块

项目的目录下

npm install npm库的key
//比如我上传的yeejava库
npm i yeejava
//如果安装时想指定特定的版本
npm i yeejava@1.x.x

安装之后的目录

node_modules

安装会自动在项目目录下添加 package-lock.json文件,这个文件帮助锁定安装包的版本

文件中,依赖包会被添加到dependencies节点下,类似maven中的

调用 的时候直接写模块名即可

const m = require('yeejava')
m.hello();

修改npm镜像

推荐使用淘宝 NPM 镜像 http://npm.taobao.org/

#经过下面的配置,以后所有的 npm install 都会经过淘宝的镜像地址下载
npm config set registry https://registry.npm.taobao.org 

#查看npm配置信息
npm config list

其它命令

#更新包(更新到最新版本)
npm update 包名
#全局更新
npm update -g 包名

#卸载包
npm uninstall 包名
#全局卸载
npm uninstall -g 包名

下载依赖
npm install

cnpm(暂不安装)

npm 命令用于从国外的服务器上下载别人做好的模块

国外的服务器,有的时候网速会很受影响

这个时候就会用到 cnpm了。这里的c 是 copy的意思,即复制 npm 上面的库

-g 是-global 的意思,即全局安装

npm install -g cnpm --registry=https://registry.npm.taobao.org

cnpm -v 查看版本号

安装模块和npm一样,只是在前面加个c

cnpm install yeejava

webpack

前端工程必须先初始化 cnpm init -y

是一个前端资源加载/打包工具。它将根据模块的依赖关系进行静态分析,

然后将这些模块按照指定的规则生成对应的静态资源

项目目录名称 不要用 webpack ,会对 webpack 工具的使用产生冲突

安装webpage

npm install -g webpack webpack-cli

全局安装(不推荐)

npm install webpack webpack-cli -g

//或指定版本,类似这样:

npm install webpack@4.16.5  webpack-cli -g
//全局卸载
npm uninstall webpack webpack-cli -g

本地安装

npm install webpack webpack-cli --save-dev
//或者
npm install webpack webpack-cli -D
//或者指定版本
npm install webpack@4.16.5 webpack-cli -D
//本地卸载
npm uninstall webpack webpack-cli -D

创建配置文件webpack.config.js

const path = require("path"); //Node.js内置模块
module.exports = {
    entry: './src/main.js', //配置入口文件
    output: {
        path: path.resolve(__dirname, './dist'), //输出路径,__dirname:当前文件所在路径
        filename: 'bundle.js' //输出文件
    }
}

执行编译命令

webpack --mode=development #没有警告

打包完成,导入js即可

打包css

src文件创建style.css

修改main.js

在第一行引入style.css

require('./style.css');

设置淘宝镜像

直接使用 npm install 安装所有依赖,所以我的做法是在项目内添加一个 .npmrc 文件:

sass_binary_site=https://npm.taobao.org/mirrors/node-sass/
phantomjs_cdnurl=https://npm.taobao.org/mirrors/phantomjs/
electron_mirror=https://npm.taobao.org/mirrors/electron/
registry=https://registry.npm.taobao.org
评论