encoder.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import {jsEncoder} from '../libs/drpyS.js';
  2. import {readFileSync, writeFileSync} from 'fs';
  3. // 检测命令行参数
  4. const args = process.argv.slice(2);
  5. if (args.length > 0) {
  6. // 如果有参数,读取文件并打印内容
  7. const filePath = args[0]; // 第一个参数作为文件路径
  8. let content = readFileSync(filePath, 'utf8');
  9. console.log(`文件 ${filePath} 的内容长度为:${content.length}`);
  10. writeFileSync(filePath + '.gz', jsEncoder.gzip(content), 'utf-8');
  11. }
  12. // 仅仅支持json post 如: {"type":"gzip","code":"xxx"}
  13. export default (fastify, options, done) => {
  14. // 注册 POST 路由
  15. fastify.post('/encoder', async (request, reply) => {
  16. const {code, type} = request.body;
  17. if (!code || !type) {
  18. return reply.status(400).send({error: 'Missing required parameters: code and type'});
  19. }
  20. // 检查文本大小
  21. const textSize = Buffer.byteLength(code, 'utf8'); // 获取 UTF-8 编码的字节大小
  22. if (textSize > options.MAX_TEXT_SIZE) {
  23. return reply
  24. .status(400)
  25. .send({error: `Text content exceeds the maximum size of ${options.MAX_TEXT_SIZE / 1024} KB`});
  26. }
  27. try {
  28. let result;
  29. switch (type) {
  30. case 'base64':
  31. result = jsEncoder.base64Encode(code);
  32. break;
  33. case 'gzip':
  34. result = jsEncoder.gzip(code);
  35. break;
  36. case 'aes':
  37. result = jsEncoder.aes_encrypt(code);
  38. break;
  39. case 'rsa':
  40. result = jsEncoder.rsa_encode(code);
  41. break;
  42. default:
  43. throw new Error(`Unsupported type: ${type}`);
  44. }
  45. reply.send({success: true, result});
  46. } catch (error) {
  47. reply.status(500).send({error: error.message});
  48. }
  49. });
  50. done();
  51. };