Skip to content

Commit 30c7efb

Browse files
committed
Rewrite for koa 2
1 parent b28dd01 commit 30c7efb

8 files changed

Lines changed: 250 additions & 233 deletions

File tree

lib/fileManager.js

Lines changed: 40 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,56 @@
1-
var fs = require('co-fs');
2-
var co = require('co');
3-
var fse = require('co-fs-extra');
4-
var path = require('path');
5-
var JSZip = require('jszip');
1+
const fs = require('fs-extra');
2+
const path = require('path');
3+
const JSZip = require('jszip');
64

7-
var FileManager = {};
5+
const FileManager = {};
86

9-
FileManager.getStats = function *(p) {
10-
var stats = yield fs.stat(p);
7+
FileManager.getStats = async p => {
8+
const stats = fs.statSync(p);
119
return {
1210
folder: stats.isDirectory(),
1311
size: stats.size,
1412
mtime: stats.mtime.getTime()
1513
}
1614
};
1715

18-
FileManager.list = function *(dirPath) {
19-
var files = yield fs.readdir(dirPath);
20-
var stats = [];
21-
for (var i=0; i<files.length; ++i) {
22-
var fPath = path.join(dirPath, files[i]);
23-
var stat = yield FileManager.getStats(fPath);
16+
FileManager.list = async dirPath => {
17+
const files = await fs.readdir(dirPath);
18+
const stats = [];
19+
for (let i = 0; i < files.length; ++i) {
20+
const fPath = path.join(dirPath, files[i]);
21+
const stat = await FileManager.getStats(fPath);
2422
stat.name = files[i];
2523
stats.push(stat);
2624
}
2725
return stats;
2826
};
2927

30-
FileManager.remove = function *(p) {
31-
yield fse.remove(p);
28+
FileManager.remove = async p => {
29+
await fs.remove(p);
3230
};
3331

34-
FileManager.mkdirs = function *(dirPath) {
35-
yield fse.mkdirs(dirPath);
32+
FileManager.mkdirs = async dirPath => {
33+
await fs.mkdirs(dirPath);
3634
};
3735

38-
FileManager.move = function *(srcs, dest) {
39-
for (var i=0; i<srcs.length; ++i) {
40-
var basename = path.basename(srcs[i]);
41-
yield fse.move(srcs[i], path.join(dest, basename));
36+
FileManager.move = async (srcs, dest) => {
37+
for (let i = 0; i < srcs.length; ++i) {
38+
const basename = path.basename(srcs[i]);
39+
await fs.move(srcs[i], path.join(dest, basename));
4240
}
4341
};
4442

45-
FileManager.rename = function *(src, dest) {
46-
yield fse.move(src, dest);
43+
FileManager.rename = async (src, dest) => {
44+
await fs.move(src, dest);
4745
};
4846

49-
FileManager.archive = function *(src, archive, dirPath, embedDirs) {
50-
var zip = new JSZip();
51-
var baseName = path.basename(archive, '.zip');
47+
FileManager.archive = async (src, archive, dirPath, embedDirs) => {
48+
const zip = new JSZip();
49+
const baseName = path.basename(archive, '.zip');
5250

53-
function* addFile(file) {
54-
var data = yield fs.readFile(file);
55-
var name;
51+
const addFile = async file => {
52+
const data = await fs.readFile(file);
53+
let name;
5654
if (embedDirs) {
5755
name = file;
5856
if (name.indexOf(dirPath) === 0) {
@@ -65,30 +63,30 @@ FileManager.archive = function *(src, archive, dirPath, embedDirs) {
6563
C.logger.info('Added ' + name + ' ' + data.length + ' bytes to archive ' + archive);
6664
}
6765

68-
function* addDir(dir) {
69-
var contents = yield fs.readdir(dir);
70-
for (var file of contents) {
71-
yield * process(path.join(dir, file));
66+
const addDir = async dir => {
67+
const contents = await fs.readdir(dir);
68+
for (const file of contents) {
69+
await process(path.join(dir, file));
7270
}
7371
}
7472

75-
function* process(fp) {
76-
var stat = yield fs.stat(fp);
73+
const process = async fp => {
74+
const stat = await fs.stat(fp);
7775
if (stat.isDirectory()) {
78-
yield * addDir(fp);
76+
await addDir(fp);
7977
} else {
80-
yield addFile(fp);
78+
await addFile(fp);
8179
}
8280
}
8381

8482
// Add each src. For directories, do the entire recursive dir.
85-
for (var file of src) {
86-
yield * process(file);
83+
for (const file of src) {
84+
await process(file);
8785
}
8886

8987
// Generate the zip and store the final.
90-
var data = yield zip.generateAsync({type:'nodebuffer',compression:'DEFLATE'});
91-
yield fs.writeFile(archive, data, 'binary');
88+
const data = await zip.generateAsync({type:'nodebuffer',compression:'DEFLATE'});
89+
await fs.writeFile(archive, data, 'binary');
9290
};
9391

9492
module.exports = FileManager;

lib/fileMap.js

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
1-
var path = require('path');
1+
const path = require('path');
22

3-
var DATA_ROOT = C.data.root;
3+
const DATA_ROOT = C.data.root;
44

5-
exports.filePath = function (relPath, decodeURI) {
6-
if (decodeURI) relPath = decodeURIComponent(relPath);
7-
if (relPath.indexOf('..') >= 0){
8-
var e = new Error('Do Not Contain .. in relPath!');
5+
exports.filePath = (relPath, decodeURI) => {
6+
if (decodeURI) {
7+
relPath = decodeURIComponent(relPath);
8+
}
9+
if (relPath.indexOf('..') >= 0) {
10+
const e = new Error('Do Not Contain .. in relPath!');
911
e.status = 400;
1012
throw e;
11-
}
12-
else {
13+
} else {
1314
return path.join(DATA_ROOT, relPath);
1415
}
1516
};

lib/index.js

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
#!/usr/bin/env node
22

3-
var koa =require('koa');
4-
var path = require('path');
5-
var tracer = require('tracer');
6-
var mount = require('koa-mount');
7-
var morgan = require('koa-morgan');
8-
var koaStatic = require('koa-static');
3+
const path = require('path');
4+
const koa = require('koa');
5+
const render = require('koa-ejs');
6+
const tracer = require('tracer');
7+
const morgan = require('koa-morgan');
8+
const koaStatic = require('koa-static');
9+
10+
const dev = process.env.NODE_ENV !== 'production';
911

1012
// Config
11-
var argv = require('optimist')
13+
const argv = require('optimist')
1214
.usage([
1315
'USAGE: $0 [-p <port>] [-d <directory>]']
1416
)
@@ -27,7 +29,7 @@ var argv = require('optimist')
2729
})
2830
.option('help', {
2931
alias: 'h',
30-
description: "Display This Help Message"
32+
description: 'Display This Help Message'
3133
})
3234
.argv;
3335

@@ -50,22 +52,27 @@ global.C = {
5052
};
5153

5254
// Start Server
53-
var Tools = require('./tools');
54-
55-
var startServer = function (app, port) {
56-
app.listen(port);
57-
C.logger.info('listening on *.' + port);
58-
};
55+
const Tools = require('./tools');
5956

60-
var app = koa();
57+
const app = new koa();
6158
app.proxy = true;
62-
app.use(Tools.handelError);
59+
render(app, {
60+
root: path.join(__dirname, 'views'),
61+
layout: false,
62+
viewExt: 'html',
63+
cache: !dev,
64+
debug: dev
65+
});
6366
app.use(Tools.realIp);
64-
app.use(morgan.middleware(C.morganFormat));
67+
app.use(Tools.handelError);
68+
app.use(morgan(C.morganFormat));
6569

66-
var IndexRouter = require('./routes');
67-
app.use(mount('/', IndexRouter));
70+
const router = require('./routes');
71+
app.use(router.routes()).use(router.allowedMethods());
6872
app.use(koaStatic(path.join(__dirname,'./public/')));
69-
70-
startServer(app, +argv.port);
71-
73+
app.listen(+argv.port, err => {
74+
if (err) {
75+
throw err;
76+
}
77+
C.logger.info('listening on *.' + argv.port);
78+
});

lib/public/js/app.js

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',
2222
var hash2paths = function (relPath) {
2323
var paths = [];
2424
var names = relPath.split('/');
25-
var path = '#/';
25+
var path = '#!/';
2626
paths.push({name: 'Home', path: path});
2727
for (var i=0; i<names.length; ++i) {
2828
var name = names[i];
@@ -50,8 +50,8 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',
5050

5151
var setCurFiles = function (relPath) {
5252
$http.get('api' + relPath)
53-
.success(function (data) {
54-
var files = data;
53+
.then(function (res) {
54+
var files = res.data;
5555
files.forEach(function (file) {
5656
file.relPath = relPath + encodeURIComponent(file.name);
5757
if (file.folder) file.relPath += '/';
@@ -60,11 +60,9 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',
6060
file.humanTime = humanTime(file.mtime);
6161
});
6262
FM.curFiles = files;
63-
console.log('Current Files:');
64-
console.log(FM.curFiles);
65-
})
66-
.error(function (data, status) {
67-
alert('Error: ' + status + data);
63+
console.log('Current Files:', FM.curFiles);
64+
}, function (res) {
65+
alert('Error: ' + res.status + res.data);
6866
});
6967
};
7068

@@ -73,7 +71,7 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',
7371
return $location.path('/');
7472
}
7573
console.log('Hash change: ' + hash);
76-
var relPath = hash.slice(1);
74+
var relPath = hash.slice(2);
7775
FM.curHashPath = hash;
7876
FM.curFolderPath = relPath;
7977
FM.curBreadCrumbPaths = hash2paths(relPath);
@@ -126,12 +124,11 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',
126124
}
127125
console.log('request url', url);
128126
$http(conf)
129-
.success(function (data) {
130-
FM.successData = data;
127+
.then(function (res) {
128+
FM.successData = res.data;
131129
handleHashChange(FM.curHashPath);
132-
})
133-
.error(function (data, status) {
134-
FM.errorData = ' ' + status + ': ' + data;
130+
}, function (res) {
131+
FM.errorData = ' ' + res.status + ': ' + res.data;
135132
});
136133
};
137134

@@ -208,14 +205,18 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',
208205
};
209206

210207
FM.upload = function () {
208+
var folder = FM.curFolderPath;
211209
console.log('Upload File:', FM.uploadFile);
212-
var formData = new FormData();
213-
formData.append('upload', FM.uploadFile);
214-
var url = 'api' + FM.curFolderPath + encodeURI(FM.uploadFile.name);
215-
httpRequest('POST', url, {type: 'UPLOAD_FILE'}, formData, {
216-
transformRequest: angular.identity,
217-
headers: {'Content-Type': undefined}
218-
});
210+
for (var i = 0; i < FM.uploadFile.length; i++) {
211+
var file = FM.uploadFile[i];
212+
var formData = new FormData();
213+
formData.append('upload', file);
214+
var url = 'api' + folder + encodeURI(file.name);
215+
httpRequest('POST', url, {type: 'UPLOAD_FILE'}, formData, {
216+
transformRequest: angular.identity,
217+
headers: {'Content-Type': undefined}
218+
});
219+
}
219220
};
220221

221222
FM.btnDisabled = function (btnName) {

0 commit comments

Comments
 (0)