word.js 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * 代码来源:http://www.thinkphp.cn/topic/27567.html
  3. * 如需编译请使用 pkg -t node12-win word.js 命令编译成word.exe文件
  4. */
  5. var service = {
  6. http: require('http'),
  7. url: require('url'),
  8. querystring: require('querystring'),
  9. fs: require('fs'),
  10. config: {
  11. timeout: 60000,
  12. charset: 'utf8',
  13. port: 10101,
  14. host: '127.0.0.1'
  15. },
  16. router: {
  17. index: function (res, query) {
  18. res.end('Server is running!');
  19. },
  20. check: function (res, query) {
  21. var result = {status: 1, info: 'success'};
  22. result = JSON.stringify(result);
  23. if (typeof query.callback == 'string') {
  24. result = query.callback + '(' + result + ')';
  25. }
  26. res.end(result);
  27. },
  28. word: function (res, query) {
  29. var _this = service;
  30. var result = {status: 0, info: 'error'};
  31. if (typeof query.file == 'string') {
  32. var img = query.file.match(/file:\/\/+(localhost)?(\S+\.(png|jpg|jpeg|gif|bmp))/i);
  33. console.log(img);
  34. if (img) {
  35. var base64 = _this.base64_encode(img[2]);
  36. result.status = 1;
  37. result.index = query.index;
  38. result.info = 'data:image/' + img[3] + ';base64,' + base64;
  39. }
  40. }
  41. result = JSON.stringify(result);
  42. if (typeof query.callback == 'string') {
  43. result = query.callback + '(' + result + ')';
  44. }
  45. res.end(result);
  46. }
  47. },
  48. start: function () {
  49. var _this = this;
  50. var Server = _this.http.createServer(function (req, res) {
  51. var URL = _this.url.parse(req.url);
  52. var receive = [];
  53. var router = null;
  54. switch (URL.pathname) {
  55. case '/word':
  56. router = _this.router.word;
  57. break;
  58. case '/check':
  59. router = _this.router.check;
  60. break;
  61. default:
  62. router = _this.router.index;
  63. }
  64. req.setEncoding(_this.config.charset);
  65. req.addListener('data', function (data) {
  66. receive.push(data);
  67. });
  68. res.writeHead(200, {'Content-Type': 'text/plain'});
  69. res.on("close", function () {
  70. console.log("res closed");
  71. });
  72. req.on("close", function () {
  73. console.log("req closed");
  74. });
  75. req.addListener('end', function () {
  76. router(res, _this.querystring.parse(URL.query));
  77. });
  78. });
  79. Server.listen(_this.config.port, _this.config.host, 1024);
  80. Server.setTimeout(_this.config.timeout, function (cli) {
  81. cli.end('timeout\n');
  82. });
  83. console.log('Server running at http://' + _this.config.host + ':' + _this.config.port);
  84. },
  85. //base64
  86. base64_encode: function (file) {
  87. var bitmap = this.fs.readFileSync(file);
  88. return new Buffer.from(bitmap).toString('base64');
  89. }
  90. };
  91. service.start();