nodejs将vue的dist目录文件copy到目标目录

  目录

利用nodejs拷贝转移文件

nodejs将vue的dist目录文件copy到目标目录

上篇文章写了《window批处理执行webpack打包》,这篇文章主要写打包好的文件自动转移到git目录下。
其实就是用的nodejs的读写文件API而已,代码不多,见下面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
let fs = require('fs');
let fse = require('fs-extra') // 文件的正删改查模块,比原生方便
let path = require('path');

// 复制文件
var copy=function(src,dst){
let paths = fs.readdirSync(src); //同步读取当前目录
paths.forEach(function(path){
var _src=src+'/'+path;
var _dst=dst+'/'+path;
fs.stat(_src,function(err,stats){ //stats 该对象 包含文件属性
if(err)throw err;
if(stats.isFile()){ //如果是个文件则拷贝
let _dst = dst+'/' + path;
let readable=fs.createReadStream(_src);//创建读取流
let writable=fs.createWriteStream(_dst);//创建写入流
readable.pipe(writable);
}else if(stats.isDirectory()){ //是目录则 递归
checkDirectory(_src,_dst,copy);
}
});
});
}
// 检查文件夹是否存在,新建文件夹并copy
var checkDirectory=function(src,dst,callback){
fs.access(dst, fs.constants.F_OK, (err) => {
if(err){
fs.mkdirSync(dst);
callback(src,dst);
}else{
callback(src,dst);
}
});
};

// 删除旧文件
var cleanOld = function(dest) {
let dest_static = path.join(dest, 'static');
let dest_index = path.join(dest, 'index.html');
fs.exists(dest_static,function(exists){
if(exists) fse.removeSync(dest_static);
});
fs.exists(dest_index,function(exists){
if(exists) fse.removeSync(dest_index);
});
}

// 文件路径
let url_src_ehome = path.relative(__dirname, 'C:\\WORK\\new-airport\\6 编码\\5 Web\\ejashop\\dist\\'),
url_dest_ehome = path.relative(__dirname, 'C:\\Users\\kaiya\\Desktop\\公司文件\\gitlang\\langcnew\\demo2\\ehome'),
url_src_airport = path.relative(__dirname, 'C:\\WORK\\new-airport\\6 编码\\5 Web\\airport\\dist\\'),
url_dest_airport = path.relative(__dirname, 'C:\\Users\\kaiya\\Desktop\\公司文件\\gitlang\\langcnew\\demo2\\airport'),
url_src_operation = path.relative(__dirname, 'C:\\WORK\\new-airport\\6 编码\\5 Web\\eHomeOperation\\dist\\'),
url_dest_operation = path.relative(__dirname, 'C:\\Users\\kaiya\\Desktop\\公司文件\\gitlang\\langcnew\\demo2\\operation'),
url_src_openShop = path.relative(__dirname, 'C:\\WORK\\new-airport\\6 编码\\5 Web\\kaidian\\dist\\'),
url_dest_openShop = path.relative(__dirname, 'C:\\Users\\kaiya\\Desktop\\公司文件\\gitlang\\langcnew\\demo2\\openShop');

// copy之前先清空旧文件
cleanOld(url_dest_ehome);
cleanOld(url_dest_airport);
cleanOld(url_dest_operation);
cleanOld(url_dest_openShop);

// 4个项目的copy转移
checkDirectory(url_src_ehome, url_dest_ehome,copy);
checkDirectory(url_src_airport, url_dest_airport,copy);
checkDirectory(url_src_operation, url_dest_operation,copy);
checkDirectory(url_src_openShop, url_dest_openShop,copy);

这里需要注意一点,path.relative(__dirname, ‘C:\WORK\new-airport\6 编码\5 Web\ejashop\dist\‘);利用path模块将两个绝对路径变成相对路径。