nodejs.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package service
  2. import (
  3. "time"
  4. "github.com/langgenius/dify-sandbox/internal/core/runner/nodejs"
  5. runner_types "github.com/langgenius/dify-sandbox/internal/core/runner/types"
  6. "github.com/langgenius/dify-sandbox/internal/static"
  7. "github.com/langgenius/dify-sandbox/internal/types"
  8. )
  9. func RunNodeJsCode(code string, preload string, options *runner_types.RunnerOptions) *types.DifySandboxResponse {
  10. if err := checkOptions(options); err != nil {
  11. return types.ErrorResponse(-400, err.Error())
  12. }
  13. timeout := time.Duration(
  14. static.GetDifySandboxGlobalConfigurations().WorkerTimeout * int(time.Second),
  15. )
  16. runner := nodejs.NodeJsRunner{}
  17. stdout, stderr, done, err := runner.Run(code, timeout, nil, preload, options)
  18. if err != nil {
  19. return types.ErrorResponse(-500, err.Error())
  20. }
  21. stdout_str := ""
  22. stderr_str := ""
  23. defer close(done)
  24. defer close(stdout)
  25. defer close(stderr)
  26. for {
  27. select {
  28. case <-done:
  29. return types.SuccessResponse(&RunCodeResponse{
  30. Stdout: stdout_str,
  31. Stderr: stderr_str,
  32. })
  33. case out := <-stdout:
  34. stdout_str += string(out)
  35. case err := <-stderr:
  36. stderr_str += string(err)
  37. }
  38. }
  39. }