System module fs file operation
const fs = require('fs');
//引入文件操作模块
require('./ceshi');
//引入自己写的模块,并且执行当中的代码
//读取文件
fs.readFile('文件路径/文件名称'[,'文件编码'],callback);
callback:回调函数
//读取上一级css目录下中的base.css
fs.readFile('../css/base.css','utf-8',(err,doc)=>{
//如果文件读取发生错误,参数err的值为错误对象 否则err的值为null
//doc参数为文件内容
if(err==null){
//在控制台中输出文件内容
console.log(doc);
}
});
写入文件内容
fs.writeFile('文件路径/文件名称','数据/将要写入的内容',callback);
const content = '<h3>正在使用fs.writeFile写入文件内容</h3>';
fs.writeFile('../index.html',content,err=>{
if(err!=null){
console.log(err);
return;
}
console.log('文件内容写入成功');
})
系统模块path路径操作,可以进行路径拼接,因为不同的操作系统的路径分隔符不一样
path.join('路径','路径',...)
//导入path模块
const path = require('path');
//路径拼接
let finialPath = path.join('itcast','a','b','c.css');
//输出结果 itcast\a\b\c.css
console.log(finialPath)l;
读取文件时的路径问题:
大多数情况下使用绝对路径,因为相对路径有时候相对的是命令行工具的当前工作目录
在读取文件或者设置文件路径时都会选择绝对路径、
使用__dirname可以获取当前文件所在的绝对路径
例:
const fs=require('fs');
const path = require('path');
console.log(__dirname);
console.log(path.join(__dirname,'01.js'));
fs.readFile(path.join(__dirname,'01.js'),'utf8',(err,doc)=>{
console.log(err);
console.log(doc);
});
第三方模块:
获取第三方模块:npmjs.com:第三方模块的存储仓库
下载:npm install 模块
删除:npm uninstall 模块
全局安装与本地安装
命令行工具:全局安装
库文件:本地安装
第三方模块 nodemon
每次修改文件保存后会自动重新执行该文件
第三方模块Gulp
Gulp使用:
1.使用npm install gulp下载gulp库文件
2.在项目根目录下建立gulpfile.js文件
3.重构项目的文件夹结构src目录放置源代码文件dist目录放置建构后文件
4.在gulp.js文件中编写任务
5.在命令行工具中执行gulp任务
Gulp中提供的方法
gulp.src():获取任务要处理的文件
gulp.dest():输出文件
gulp.task():建立gulp任务
gulp.watch():监控文件的变化
const gulp = require('gulp');
//使用gulp.task()方法建立任务
gulp.task('first',()=>{
//1.任务的名称 2.任务的回调函数
//获取要处理的文件
gulp.src('./src/css/base.css');
//将处理后的文件输出到dist目录/复制
.pipe(gulp.dest('./dist/css'));
//把要处理文件的代码写到pipe中
//链式编程
})
执行gulp任务的方法:
1.用npm install gulp-cli -g下载模块
2.使用gulp 任务名字 执行gulpfile中的的任务
gulp插件
HTML任务
1.HTML文件中代码的压缩操作 下载:npm install gulp-htmlmin
2.抽取HTML文件中的公共代码 下载:npm install gulp-file-include
使用方法在官网里面找
const fileinclude = require('gulp-file-include');
const htmlmin = require('gulp-htmlmin');
gulp.task('htmlmin',()=>{
//选择所有的HTML文件,*代表所有的文件,*.html代表全部的html文件
gulp.src('./src/*.html')
//抽取公共代码,用
.pipe(fileinclude())
//collapseWhitespace:true压缩空格
.pipe(htmlmin({
collapseWhitespace:true}))
.pipe(gulp.dest('dist'));
//使用@@include('路径/文件名')可以把公共代码引入回来
})
一次性执行全部的任务
gulp.task('default',['htmlmin','cssmin']);
The role of the package.json file The
project description file records the current project information, such as the project name, version, author, and which third-party modules the current project depends on. It is generated using the npm init -y command. The dependencies are recorded in the dependencies. When there is a pack.json file, you only need to use npm install to automatically download project dependencies and development dependencies
npm install --production will only download project dependencies
Development dependency:
use npm install package name --save -dev command to add to the devDependencies field of the package.json file