forked from reruin/sharelist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
drive.fs.js
113 lines (90 loc) · 2.7 KB
/
drive.fs.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
* 提供对本地文件系统的支持
* file:linux风格路径
*/
const name = 'FileSystem'
const version = '1.0'
const protocols = ['fs' , 'file']
const defaultProtocol = 'fs'
const path = require('path')
const fs = require('fs')
const os = require('os')
const isWinOS = os.platform() == 'win32'
const l2w = (p) => p.replace(/^\/([^\/]+?)/,'$1:\\').replace(/\//g,'\\').replace(/(?<!\:)\\+$/,'').replace(/\\{2,}/g,'\\')
const realpath = (p) => (isWinOS ? l2w(p) : p)
module.exports = ({datetime , extname , pathNormalize}) => {
const normalize = (p) => pathNormalize(p).replace(/^\.\//,process.cwd()+'/')
const folder = async(id , {_path=[]} = {}) => {
let dir = normalize(id)
if( _path.length > 0) {
dir = _path.length.join('/')
}
let resp = { id : dir , type:'folder', protocol:defaultProtocol}
let realdir = realpath(dir)
if( fs.existsSync(realdir) ){
let children = []
fs.readdirSync(realdir).forEach(function(filename){
let path = normalize(dir) + '/' + filename
let stat
try{
stat = fs.statSync(realpath(path))
}catch(e){}
let obj = {
id:path ,
name:filename,
protocol:defaultProtocol,
type:'other'
}
if(stat){
obj.created_at = datetime(stat.ctime)
obj.updated_at = datetime(stat.mtime)
if(stat.isDirectory()){
obj.type = 'folder'
}
else if(stat.isFile()){
obj.ext = extname(filename)
obj.size = stat.size
}
}
children.push(obj)
})
resp.children = children
return resp
}else{
return false
}
}
const file = async(id)=>{
let realdir = realpath(normalize(id))
let stat = {}
try{
stat = fs.statSync(realpath(realdir))
}catch(e){}
return {
id,
name: path.basename(id),
ext: extname(id),
url: realpath(id),
size:stat.size,
protocol:defaultProtocol,
outputType:'file',
proxy:true
}
}
const createReadStream = ({id , options = {}} = {}) => {
return fs.createReadStream(realpath(id) , options)
}
const mkdir = (p) => {
if (fs.existsSync(p) == false) {
mkdir(path.dirname(p));
fs.mkdirSync(p);
}
};
const createWriteStream = async ({ id , options = {} , target = ''} = {}) => {
let fullpath = pathNormalize(id +'/' + target)
let parent = (fullpath.split('/').slice(0,-1).join('/') + '/').replace(/\/+$/g,'/')
mkdir(parent)
return fs.createWriteStream(realpath(fullpath) , options)
}
return { name , version , drive:{ protocols , folder , file , cache:false , createReadStream , createWriteStream } }
}