{"id":29151216,"url":"https://github.com/karpeleslab/nodejs","last_synced_at":"2025-07-01T00:08:56.073Z","repository":{"id":228111434,"uuid":"773199369","full_name":"KarpelesLab/nodejs","owner":"KarpelesLab","description":"nodejs factory and pool","archived":false,"fork":false,"pushed_at":"2025-03-22T11:44:38.000Z","size":127,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-22T12:26:56.420Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/KarpelesLab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-03-17T02:05:39.000Z","updated_at":"2025-03-22T11:44:41.000Z","dependencies_parsed_at":"2025-03-22T12:34:02.319Z","dependency_job_id":null,"html_url":"https://github.com/KarpelesLab/nodejs","commit_stats":null,"previous_names":["karpeleslab/nodejs"],"tags_count":8,"template":false,"template_full_name":null,"purl":"pkg:github/KarpelesLab/nodejs","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KarpelesLab%2Fnodejs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KarpelesLab%2Fnodejs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KarpelesLab%2Fnodejs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KarpelesLab%2Fnodejs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/KarpelesLab","download_url":"https://codeload.github.com/KarpelesLab/nodejs/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KarpelesLab%2Fnodejs/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262870877,"owners_count":23377314,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-07-01T00:08:54.346Z","updated_at":"2025-07-01T00:08:55.949Z","avatar_url":"https://github.com/KarpelesLab.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![GoDoc](https://godoc.org/github.com/KarpelesLab/nodejs?status.svg)](https://godoc.org/github.com/KarpelesLab/nodejs)\n\n# nodejs tools for Go\n\nA Go library that provides seamless integration with NodeJS, allowing Go programs to run JavaScript code through managed NodeJS instances.\n\n## Features\n\n- **NodeJS Factory**: Automatic detection and initialization of NodeJS\n- **Process Management**: Start, monitor, and gracefully terminate NodeJS processes\n- **Process Pooling**: Efficiently manage multiple NodeJS instances with auto-scaling\n- **JavaScript Execution**: Run JS code with precise control and error handling\n- **IPC Communication**: Bidirectional communication between Go and JavaScript\n- **Health Monitoring**: Built-in process health checks and responsiveness verification\n- **Isolated Contexts**: Create isolated JavaScript execution contexts within a process\n- **HTTP Integration**: Serve HTTP requests directly to JavaScript handlers\n\n## Installation\n\n```bash\ngo get github.com/KarpelesLab/nodejs\n```\n\n## Basic Usage\n\n### Creating a NodeJS Factory\n\nThe factory is responsible for finding and initializing NodeJS:\n\n```go\nfactory, err := nodejs.New()\nif err != nil {\n    // handle error: nodejs could not be found or didn't run\n}\n```\n\n### Direct Process Management\n\nCreate and manage individual NodeJS processes:\n\n```go\n// Create a new process with default timeout (5 seconds)\nprocess, err := factory.New()\nif err != nil {\n    // handle error\n}\ndefer process.Close()\n\n// Run JavaScript without waiting for result\nprocess.Run(\"console.log('Hello from NodeJS')\", nil)\n\n// Evaluate JavaScript and get result\nctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\ndefer cancel()\nresult, err := process.Eval(ctx, \"2 + 2\", nil)\nif err != nil {\n    // handle error\n}\nfmt.Println(\"Result:\", result) // Output: Result: 4\n```\n\n### Process Pool\n\nFor applications that need to execute JavaScript frequently, using a pool improves performance:\n\n```go\n// Create a pool with auto-sized queue (defaults to NumCPU)\npool := factory.NewPool(0, 0)\n\n// Get a process from the pool (waits if none available)\nctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\ndefer cancel()\nprocess, err := pool.Take(ctx)\nif err != nil {\n    // handle error: timeout or context cancelled\n}\ndefer process.Close() // Returns process to pool\n\n// Execute JavaScript using the pooled process\nresult, err := process.Eval(ctx, \"(() =\u003e { return 'Hello from pooled NodeJS'; })()\", nil)\nif err != nil {\n    // handle error\n}\nfmt.Println(result)\n```\n\n### Bidirectional IPC\n\nRegister Go functions that can be called from JavaScript:\n\n```go\nprocess.SetIPC(\"greet\", func(params map[string]any) (any, error) {\n    name, _ := params[\"name\"].(string)\n    if name == \"\" {\n        name = \"Guest\"\n    }\n    return map[string]any{\n        \"message\": fmt.Sprintf(\"Hello, %s!\", name),\n    }, nil\n})\n\n// In JavaScript, call the Go function:\nprocess.Run(`\n    async function testIPC() {\n        const result = await ipc('greet', { name: 'World' });\n        console.log(result.message); // Outputs: Hello, World!\n    }\n    testIPC();\n`, nil)\n```\n\n### Advanced Features\n\n#### Isolated JavaScript Contexts\n\nJavaScript contexts provide isolated execution environments within a single NodeJS process:\n\n```go\n// Create a NodeJS process\nproc, err := factory.New()\nif err != nil {\n    // handle error\n}\ndefer proc.Close()\n\n// Create an isolated JavaScript context\njsCtx, err := proc.NewContext()\nif err != nil {\n    // handle error\n}\ndefer jsCtx.Close()\n\n// Execute JavaScript in the context\nctx := context.Background()\nresult, err := jsCtx.Eval(ctx, \"var counter = 1; counter++;\", nil)\nif err != nil {\n    // handle error\n}\nfmt.Println(\"Result:\", result) // Output: Result: 2\n\n// Create a second isolated context\njsCtx2, err := proc.NewContext()\nif err != nil {\n    // handle error\n}\ndefer jsCtx2.Close()\n\n// The second context has its own independent environment\nresult2, err := jsCtx2.Eval(ctx, \"typeof counter\", nil)\nif err != nil {\n    // handle error\n}\nfmt.Println(\"Result2:\", result2) // Output: Result2: undefined\n```\n\n#### HTTP Integration with JavaScript Handlers\n\nYou can serve HTTP requests directly to JavaScript handlers using two approaches:\n\n**Method 1: Using Context ServeHTTPToHandler**\n\n```go\n// Create a JavaScript context\njsCtx, err := proc.NewContext()\nif err != nil {\n    // handle error\n}\ndefer jsCtx.Close()\n\n// Define a JavaScript HTTP handler\n_, err = jsCtx.Eval(context.Background(), `\n// Define a handler function\nthis.apiHandler = function(request) {\n    // Create response body\n    const body = JSON.stringify({\n        message: \"Hello, World!\",\n        method: request.method,\n        path: request.url\n    });\n    \n    // Return a Response object (Fetch API compatible)\n    return new Response(body, {\n        status: 200,\n        headers: {\n            \"Content-Type\": \"application/json\"\n        }\n    });\n};\n`, nil)\n\n// Create an HTTP handler that delegates to the JavaScript context\nhttp.HandleFunc(\"/api\", func(w http.ResponseWriter, r *http.Request) {\n    jsCtx.ServeHTTPToHandler(\"apiHandler\", w, r)\n})\n\n// Start the HTTP server\nhttp.ListenAndServe(\":8080\", nil)\n```\n\n**Method 2: Using Process ServeHTTPWithOptions**\n\nThis approach allows specifying the context separately for better separation of concerns:\n\n```go\n// Create a JavaScript context for API handlers\napiContext, err := proc.NewContext()\nif err != nil {\n    // handle error\n}\ndefer apiContext.Close()\n\n// Define a handler in the context\n_, err = apiContext.Eval(context.Background(), `\n// API handler\nthis.handler = function(request) {\n    return new Response(JSON.stringify({\n        message: \"Hello from API\"\n    }), {\n        status: 200,\n        headers: { \"Content-Type\": \"application/json\" }\n    });\n};\n`, nil)\n\n// Create an HTTP handler using ServeHTTPWithOptions\nhttp.HandleFunc(\"/api\", func(w http.ResponseWriter, r *http.Request) {\n    // Specify options with the context ID\n    options := nodejs.HTTPHandlerOptions{\n        Context: apiContext.ID(),\n    }\n    \n    // Call the handler directly with the context in options\n    proc.ServeHTTPWithOptions(\"handler\", options, w, r)\n})\n\n// Start the HTTP server\nhttp.ListenAndServe(\":8080\", nil)\n```\n\n#### Custom Timeouts\n\n```go\n// Create process with custom initialization timeout\nprocess, err := factory.NewWithTimeout(10 * time.Second)\nif err != nil {\n    // handle error\n}\n```\n\n#### Health Checks\n\n```go\n// Verify process is responsive\nif err := process.Checkpoint(2 * time.Second); err != nil {\n    // Process is not responding\n    process.Kill() // Force terminate if needed\n}\n```\n\n#### Module Support\n\n```go\n// Execute ES modules\nprocess.Run(`\n    import { createHash } from 'crypto';\n    const hash = createHash('sha256').update('hello').digest('hex');\n    console.log(hash);\n`, map[string]any{\"filename\": \"example.mjs\"})\n```\n\n## License\n\nSee the LICENSE file for details.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarpeleslab%2Fnodejs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkarpeleslab%2Fnodejs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarpeleslab%2Fnodejs/lists"}