modifyFile.js
2.59 KB
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
var express = require('express');
var router = express.Router();
var AWS = require('aws-sdk');
AWS.config.loadFromPath(__dirname + "/../modules/awsconfig.json");
var S3 = require('../modules/s3/s3');
var fs = require('fs');
var moment = require('moment');
// /file/modify/:name
router.post('/:name', function(req, res){
var user_id = req.body.user_id;
var curPath = req.body.cur; // /folder1/folder2/
var file_name = req.params.name;
var modified_name = req.body.name;
var modified_content = req.body.content;
var targetPath;
if (curPath == '/') {
targetPath = '';
} else {
targetPath = curPath.substring(1, curPaht.length-1); // folder1/folder2
}
var originalDir = __dirname + '/../modules/s3/download/' + user_id + curPath + file_name;
var tempDownloadDir;
// 파일 이름 변경
S3.renameFile(S3.BUCKET_NAME, user_id, file_name, modified_name, targetPath, function(result, r_modified_name){
if (result){
modified_name = r_modified_name;
tempDownloadDir = __dirname + '/../modules/s3/download/' + user_id + curPath + modified_name;
fs.unlink(originalDir, function(err){
if (err){
console.log(err);
res.send({error: 'original file not exists in server'});
}else{
// 파일 내용 변경
fs.writeFileSync(tempDownloadDir, modified_content);
S3.coverFile(S3.BUCKET_NAME, user_id, modified_name, targetPath, tempDownloadDir, function (result) {
if (result) {
var sql = 'UPDATE files SET file_name=(?), updated=(?), recent_access=(?) WHERE user_id=(?) AND location=(?) AND file_name=(?)';
connection.query(sql, [modified_name, moment().format(), moment().format(), user_id, curPath, file_name], function (err) {
if (err) {
console.log(err);
res.send({ error: 'update error' });
} else {
fs.unlinkSync(tempDownloadDir);
res.send('modify file success');
}
})
} else {
res.send({ error: 'modify file failed' });
}
})
}
});
}else{
res.send({error: 'rename error'});
}
})
});
module.exports = router;