file-api.lua 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. return function (connection, req, args)
  2. dofile('httpserver-header.lc')(connection, 200, 'html')
  3. if req.method == 'POST' then
  4. --print('POST method')
  5. local rd = req.getRequestData()
  6. --print(node.heap())
  7. collectgarbage()
  8. --print(node.heap())
  9. if rd['action'] == 'list' then
  10. print('retrieve file list')
  11. local l, filelist, n, s, ok, json
  12. l = file.list()
  13. filelist = {}
  14. for n, s in pairs(l) do
  15. if ((string.sub(n, -3) ~= '.gz') and (string.sub(n, -3) ~= '.lc')) then
  16. filelist[n] = s
  17. end
  18. end
  19. ok, json = pcall(cjson.encode, filelist)
  20. if ok then
  21. --print(json)
  22. connection:send(json)
  23. else
  24. --print("failed to encode!")
  25. end
  26. elseif rd['action'] == 'load' then
  27. print('load file: '..rd['filename'])
  28. file.open(rd['filename'], 'r')
  29. local buffer = file.read()
  30. while buffer ~= nil do
  31. connection:send(buffer)
  32. buffer = file.read()
  33. end
  34. file.close()
  35. elseif rd['action'] == 'save' then
  36. print('save file: '..rd['filename'])
  37. local data = rd['data']
  38. file.open(rd['filename'], 'w+')
  39. file.write(data)
  40. file.close()
  41. connection:send('initial write: ' .. string.len(data))
  42. elseif rd['action'] == 'append' then
  43. print('append file: '..rd['filename'])
  44. local data = rd['data']
  45. file.open(rd['filename'], 'a+')
  46. file.seek('end')
  47. file.write(data)
  48. file.close()
  49. connection:send('append: ' .. string.len(data))
  50. elseif rd['action'] == 'compile' then
  51. print('compile file: '..rd['filename'])
  52. node.compile(rd['filename'])
  53. end
  54. end
  55. collectgarbage()
  56. end