14-includes-execd.agi 1.4 KB

123456789101112131415161718192021222324252627
  1. /*---
  2. title: Includes and background jobs
  3. group: Request modes
  4. summary: Share code with includes() and start a detached script with execd().
  5. setup: {"files":[{"path":"web:/Playground/lib/format.js","text":"// Shared helpers, loaded with includes(\"lib/format.js\").\nfunction formatBytes(n){\n var units = [\"B\", \"KB\", \"MB\", \"GB\"];\n var i = 0;\n while (n >= 1024 && i < units.length - 1){ n = n / 1024; i++; }\n return (Math.round(n * 10) / 10) + \" \" + units[i];\n}\n"},{"path":"web:/Playground/jobs/cleanup.agi","text":"requirelib(\"filelib\");\nvar log = \"Cleanup ran for \" + USERNAME + \" with payload \" + PARENT_PAYLOAD + \"\\n\";\nif (!filelib.fileExists(\"user:/Logs\")) { filelib.mkdir(\"user:/Logs\"); }\nfilelib.writeFile(\"user:/Logs/cleanup.log\", log);\nconsole.log(\"cleanup.agi finished\");\n"}]}
  6. ---*/
  7. /*
  8. includes() loads another script of the same WebApp into this one.
  9. execd() starts a script in the background: the response does not wait
  10. for it, and it gets PARENT_DETACHED and PARENT_PAYLOAD.
  11. */
  12. requirelib("filelib");
  13. includes("lib/format.js");
  14. var files = filelib.walk("user:/", "file");
  15. var total = 0;
  16. for (var i = 0; i < files.length; i++) {
  17. total += filelib.filesize(files[i]);
  18. }
  19. execd("jobs/cleanup.agi", JSON.stringify({ files: files.length }));
  20. sendJSONResp({
  21. files: files.length,
  22. used: formatBytes(total),
  23. background: "jobs/cleanup.agi started; see Changes for user:/Logs/cleanup.log"
  24. });