getData.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. var actions = require("./action/index");
  2. module.exports = function(request, response) {
  3. var pathname = request.pathname;
  4. if(request.method === 'OPTIONS') {
  5. response.end();
  6. }else if(actions.hasOwnProperty(pathname)) {
  7. if(pathname === '/file/upload') {
  8. response.writeHead(200, {
  9. "Content-Type": "application/json;charset=UTF-8"
  10. });
  11. var pr = actions[pathname](request, response);
  12. pr.then(data => {
  13. response.write(JSON.stringify({
  14. code: 200,
  15. success: true,
  16. data: data
  17. }));
  18. response.end();
  19. }).catch((err) => {
  20. response.write(JSON.stringify({
  21. code: 200,
  22. success: false,
  23. data: null,
  24. msg: err
  25. }));
  26. response.end();
  27. });
  28. }else if(pathname === '/file/download') {
  29. var filename = request.query.filename;
  30. var arr = [];
  31. var readStream = actions[pathname](request, response);
  32. readStream.on('data', chunk => {
  33. arr.push(Buffer.from(chunk));
  34. });
  35. readStream.on('error', err => {
  36. response.writeHead(200, {
  37. "Content-Type": "application/json;charset=UTF-8"
  38. });
  39. response.write(JSON.stringify({
  40. code: 200,
  41. success: false,
  42. msg: err,
  43. data: null
  44. }));
  45. response.end();
  46. });
  47. readStream.on('end', () => {
  48. response.writeHead(200, {
  49. "Content-Type": "application/octet-stream",
  50. 'Content-Disposition': 'attachment; filename=' + encodeURI(filename)
  51. });
  52. response.write(Buffer.from(...arr), 'binary');//文档内容以二进制的格式写到response的输出流
  53. response.end();
  54. })
  55. }else {
  56. response.writeHead(200, {
  57. "Content-Type": "application/json;charset=UTF-8"
  58. });
  59. response.write(JSON.stringify({
  60. code: 200,
  61. success: true,
  62. data: actions[pathname](request, response)
  63. }));
  64. response.end();
  65. }
  66. }else {
  67. response.write(JSON.stringify({
  68. code: 200,
  69. success: false,
  70. msg: 'no matches.',
  71. data: null
  72. }));
  73. response.end();
  74. }
  75. }