|
1 | 1 | const fs = require('fs') |
2 | 2 | const iconv = require('iconv-lite') |
3 | | -const { dirname } = require('path') |
| 3 | +const path = require('path') |
4 | 4 |
|
5 | | -module.exports = async function read({ body }) { |
6 | | - const { encode, value, force } = body |
7 | | - |
8 | | - const path = body.path[0] === '/' ? body.path : `/${body.path}` |
9 | | - |
10 | | - if (!path) { |
11 | | - return { code: 400, msg: '缺少文件路径参数', data: body } |
| 5 | +module.exports = async function ({ body }) { |
| 6 | + if (!body.path) { |
| 7 | + return { code: 400, msg: '缺少文件路径参数' } |
12 | 8 | } |
13 | 9 |
|
| 10 | + const filePath = body.path[0] === '/' ? body.path : `/${body.path}` |
| 11 | + |
14 | 12 | try { |
15 | | - if (fs.existsSync(path)) { |
16 | | - const stat = fs.statSync(path) |
| 13 | + if (fs.existsSync(filePath)) { |
| 14 | + const stat = fs.statSync(filePath) |
17 | 15 | if (!stat.isFile()) { |
18 | | - return { code: 400, msg: '路径不是文件', data: body } |
| 16 | + return { code: 400, msg: '路径不是文件' } |
19 | 17 | } |
20 | | - |
21 | | - fs.writeFileSync(path, iconv.encode(value, encode)) |
22 | 18 | } else { |
23 | | - if (Number(force) === 1) { |
24 | | - const dir = dirname(path) |
| 19 | + if (Number(body.force) === 1) { |
| 20 | + const dir = path.dirname(filePath) |
25 | 21 | fs.existsSync(dir) || fs.mkdirSync(dir, { recursive: true }) |
26 | 22 | } else { |
27 | | - return { code: 404, msg: '文件不存在', data: body } |
| 23 | + return { code: 404, msg: '文件不存在' } |
28 | 24 | } |
29 | 25 | } |
30 | 26 |
|
31 | | - fs.writeFileSync(path, iconv.encode(value, encode)) |
| 27 | + fs.writeFileSync(filePath, iconv.encode(body.value, body.encode)) |
32 | 28 |
|
33 | | - const stat = fs.statSync(path) |
| 29 | + const stat = fs.statSync(filePath) |
34 | 30 |
|
35 | 31 | return { code: 200, msg: '操作成功', data: { size: stat.size, time: stat.mtime.toUTCString() } } |
36 | 32 | } catch (err) { |
37 | 33 | if (err.code === 'EACCES') { |
38 | | - return { code: 401, msg: '权限不足,无法写入文件', data: body } |
| 34 | + return { code: 401, msg: '权限不足,无法写入文件' } |
39 | 35 | } else if (err.code === 'ENOENT') { |
40 | | - return { code: 400, msg: '目录不存在,无法写入文件', data: body } |
| 36 | + return { code: 400, msg: '目录不存在,无法写入文件' } |
41 | 37 | } else { |
42 | | - return { code: 400, msg: `文件操作错误: ${err.message}`, data: body } |
| 38 | + return { code: 400, msg: `文件操作错误: ${err.message}` } |
43 | 39 | } |
44 | 40 | } |
45 | 41 | } |
0 commit comments