1,为什么选择Node ?
- 使用JavaScript 开发后端应用
- Node 是一个基于 Chrome V8的 JavaScript代码运行环境
4, Node.js
-
JavaScript 存在 文件依赖 和 命名冲突 的问题
-
node.js 规定 一个 JavaScript 文件就是一个模块,内部定义的变量和函数,默认情况下,在外部无法拿到
-
在模块内部可以使用 exports 导出, 使用 require 导入
a.js const add = (a,b) => a+b; console.log('hello, node.js'); exports.addFromea = add; // 也可以使用module.expots导出,都存在时,以model.expots为准 b.js const a = require('./a.js'); console.log(a.addFromea(1,2));
5, 系统模块 ---Node运行环境提供的API
-
fs文件操作
-
fs.readFile('文件路径/文件名称','utf8(编码格式)', callback)
const fs = require('fs'); fs.readFile('./a.js','utf8',(err,doc) =>{ console.log(err); console.log(doc); })
-
fs.writeFile('文件路径/文件名称','内容', callback)
const fs = require('fs'); // 当文件不存在时,会被创建 fs.writeFile('./test.txt','hello node.js',err=>{ if(err != null){ // err 非空说明出错了 console.log('失败!') return; } console.log('成功!'); })
-
注意: 上面使用的都是相对地址,相对地址其实是不安全的,当node发生改变时……,其次是,Windows 和 Linux 的系统的路径分隔符不统一,Windows \ / Linux /
路径拼接: path.join('路径',‘路径’,……);
获取当前文件所在的绝对路径: __dirname // 前面是两个 下划线
const fs = require('fs');
// 当文件不存在时,会被创建
const path = require('path')
fs.writeFile(path.join(__dirname,'./test.txt'),'hello node.js',err=>{
if(err != null){ // err 非空说明出错了
console.log('失败!')
return;
}
console.log('成功!')
})
6, 第三方模块
别人写好的,具有特定功能的,拿过来直接使用,一般含有多个文件放在同一文件夹中,所以又名包
npm (node pakage manager): node 的第三方模块管理工具
-
npm install 模块名称 // 下载
-
npm uninstall 模块名称 // 删除
-
本地安装与全局安装-------》
-
nodemon 第三方模块的使用( 保存代码后,自动再次运行)
-
npm install nodemon -g 全局下载安装
-
使用nodemon 替代 node 命令执行文件
-
按两次 ctrl + c 退出
-
切换下载地址的第三方模块 nrm
7, Gulp 的使用