{"modulePath":"github.com/KarpelesLab/nodejs","version":"v0.2.1","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package nodejs\n\n## Variables\n\n```go\nvar (\n\t// ErrTimeout is returned when a NodeJS operation exceeds its allowed time limit\n\tErrTimeout = errors.New(\"nodejs: timeout reached\")\n\n\t// ErrDeadProcess is returned when attempting to interact with a NodeJS process\n\t// that has already terminated\n\tErrDeadProcess = errors.New(\"nodejs: process has died\")\n)\n```\nPackage-level error definitions for common error conditions\n\n## Types\n\n```go\ntype Context struct {\n\t// contains filtered or unexported fields\n}\n```\nContext represents a JavaScript context within a NodeJS process. It provides sandboxed JavaScript execution that is isolated from other contexts.\n\n```go\nfunc (c *Context) Close() error\n```\nClose frees the JavaScript context in the NodeJS process. After closing, the context cannot be used for execution.\n\n```go\nfunc (c *Context) Eval(ctx context.Context, code string, opts map[string]any) (any, error)\n```\nEval executes JavaScript code within this context and returns the result. It takes a Go context for timeout/cancellation and options for execution.\n\n```go\nfunc (c *Context) EvalChannel(code string, opts map[string]any) (chan map[string]any, error)\n```\nEvalChannel executes JavaScript code within this context and returns a channel that will receive the evaluation result when available. Unlike Eval, this method doesn't wait for the result and returns immediately. The caller is responsible for monitoring the channel for results.\n\n```go\nfunc (c *Context) ID() string\n```\nID returns the unique identifier for this JavaScript context. This ID can be used when calling ServeHTTPWithOptions to specify the context in which to execute the handler function.\n\n```go\nfunc (c *Context) ServeHTTPToHandler(handlerFunc string, w http.ResponseWriter, r *http.Request)\n```\nServeHTTPToHandler serves an HTTP request to a JavaScript handler function within this context. It converts the HTTP request to a JavaScript Fetch API compatible Request, calls the specified handler, and streams the Response back to the Go ResponseWriter.\n\nThe handlerFunc parameter is the name of the JavaScript handler function to call within this context. The handler function should accept a Request object and return a Response object.\n\nExample JavaScript handler:\n\n\t// In the context:\n\thandler = function(request) {\n\t  return new Response(JSON.stringify({hello: 'world'}), {\n\t    status: 200,\n\t    headers: {'Content-Type': 'application/json'}\n\t  });\n\t}\n\n```go\ntype Factory struct {\n\t// contains filtered or unexported fields\n}\n```\nFactory represents a NodeJS instance factory that can create processes. It holds the path to the NodeJS executable and its version.\n\n```go\nfunc New() (*Factory, error)\n```\nNew creates a new NodeJS factory instance. It attempts to locate the NodeJS executable in system paths or specific locations. On Unix systems, it first checks a predefined path, then falls back to PATH search. Returns an error if NodeJS cannot be found or fails initialization checks.\n\n```go\nfunc (factory *Factory) New() (*Process, error)\n```\nNew creates a new NodeJS process with the default timeout of 5 seconds. It returns a Process that can be used to run JavaScript code.\n\n```go\nfunc (f *Factory) NewPool(queueSize, maxProcs int) *Pool\n```\nNewPool returns a pool of nodejs processes generated by the factory. The pool will always generate at least queueSize processes in memory and will start new ones as they are taken. Passing queueSize \\\u003c=0 will use the number of CPUs.\n\n```go\nfunc (factory *Factory) NewWithTimeout(timeout time.Duration) (*Process, error)\n```\nNewWithTimeout creates a new NodeJS process with a custom timeout. The timeout controls how long to wait for the NodeJS process to initialize.\n\n```go\ntype HTTPHandlerOptions struct {\n\t// Context is the ID of the JavaScript context to run the handler in.\n\t// If empty, the handler is executed in the global scope, unless the\n\t// handler name contains a dot (e.g., \"context.handler\").\n\tContext string\n}\n```\nHTTPHandlerOptions represents configuration options for an HTTP request to a JavaScript handler.\n\n```go\ntype IpcFunc func(map[string]any) (any, error)\n```\nIpcFunc is a function type for handling IPC calls from JavaScript to Go. It receives a map of parameters and returns a response or error.\n\n```go\ntype Pool struct {\n\tTimeout time.Duration // Timeout for running nodejs, defaults to 10 second if zero\n\t// contains filtered or unexported fields\n}\n```\nPool manages a pool of NodeJS processes that can be used to execute JavaScript code. It automatically maintains a queue of ready processes and creates new ones as needed.\n\n```go\nfunc (pool *Pool) Take(ctx context.Context) (*Process, error)\n```\nTake returns a [Process](#Process) from the pool and will wait until one is available, unless the context is cancelled.\n\n```go\nfunc (pool *Pool) TakeIfAvailable() *Process\n```\nTakeIfAvailable returns a Process if any is immediately available, or nil if not. This method does not wait or block if no processes are available.\n\n```go\nfunc (pool *Pool) TakeTimeout(t time.Duration) (*Process, error)\n```\nTakeTimeout will return a [Process](#Process) taken from the pool if any is available before the timeout expires.\n\n```go\ntype Process struct {\n\t*exec.Cmd // Embedded command to run NodeJS\n\t// contains filtered or unexported fields\n}\n```\nProcess represents a running NodeJS process instance. It wraps exec.Cmd and provides communication channels with the NodeJS process.\n\n```go\nfunc (p *Process) Alive() \u003c-chan struct{}\n```\nAlive returns a channel that will be closed when the NodeJS process ends. This can be used to monitor the process state and react to termination.\n\n```go\nfunc (p *Process) Checkpoint(timeout time.Duration) error\n```\nCheckpoint verifies that the NodeJS process is responsive by sending a message and waiting for a response. It returns an error if the process does not respond within the specified timeout duration. This is useful for health checks and ensuring the NodeJS process hasn't frozen.\n\n```go\nfunc (p *Process) Close() error\n```\nClose gracefully shuts down the NodeJS process by closing its stdin pipe. This allows the process to perform cleanup operations before exiting.\n\n```go\nfunc (p *Process) Console() []byte\n```\nConsole returns the console output so far for the nodejs process\n\n```go\nfunc (p *Process) Eval(ctx context.Context, code string, opts map[string]any) (any, error)\n```\nEval executes JavaScript code and returns the result of the evaluation. Unlike Run, this method waits for the code to complete execution and returns the result. It takes a context for timeout/cancellation control. If the JavaScript code throws an error, it will be returned as a Go error.\n\n```go\nfunc (p *Process) EvalChannel(code string, opts map[string]any) (chan map[string]any, error)\n```\nEvalChannel will execute the provided code and return a channel that can be used to read the response once it is made available\n\n```go\nfunc (p *Process) GetVersion(what string) string\n```\n\n```go\nfunc (p *Process) Kill()\n```\nKill forcibly terminates the NodeJS process immediately.\n\n```go\nfunc (p *Process) Log(msg string, args ...any)\n```\nLog appends a message to the nodejs console directly so it can be retrieved with Console()\n\n```go\nfunc (p *Process) MakeResponse() (string, chan map[string]any)\n```\nMakeResponse returns a handler id and a channel that will see data appended to it if triggered from the javascript side with a response event to that id. This can be useful for asynchronisous events.\n\n```go\nfunc (p *Process) NewContext() (*Context, error)\n```\nNewContext creates a new JavaScript execution context in the specified NodeJS process. It returns a Context interface that can be used to execute JavaScript code in isolation.\n\n```go\nfunc (p *Process) Run(code string, opts map[string]any)\n```\nRun executes the provided JavaScript code in the NodeJS instance. The options map can contain metadata like filename, which determines how the code is executed. If the filename ends in .mjs, the code will be executed as an ES module. This method does not return any results from the execution.\n\n```go\nfunc (p *Process) ServeHTTPToHandler(handlerFunc string, w http.ResponseWriter, r *http.Request)\n```\nServeHTTPToHandler converts an HTTP request to a JavaScript Fetch API compatible Request, calls a handler in the NodeJS process, and streams the Response back to the Go ResponseWriter.\n\nThe handlerFunc parameter is the name of the JavaScript handler function to call. If handlerFunc contains a dot (e.g., \"myContext.handler\"), the function will be called within that context. Otherwise, it will be called as a global function.\n\nThe handler function should accept a Request object (compatible with the Fetch API) and must return a Response object (also compatible with the Fetch API). For example:\n\n\t// In JavaScript:\n\tmyHandler = function(request) {\n\t  return new Response(JSON.stringify({hello: 'world'}), {\n\t    status: 200,\n\t    headers: {'Content-Type': 'application/json'}\n\t  });\n\t}\n\nThe Request and Response objects are available in both global scope and context sandboxes, and can also be imported in ES modules using:\n\n\timport { Request, Response, Headers } from 'web-api';\n\nIf an error occurs in the JavaScript handler, it will be logged and a 500 Internal Server Error will be returned, unless headers have already been written to the response.\n\nThis version supports the legacy format where context and handler are combined (context.handler). For a version that takes context separately, use ServeHTTPWithOptions.\n\n```go\nfunc (p *Process) ServeHTTPWithOptions(handlerFunc string, options HTTPHandlerOptions, w http.ResponseWriter, r *http.Request)\n```\nServeHTTPWithOptions converts an HTTP request to a JavaScript Fetch API compatible Request, calls a handler in the NodeJS process with the specified options, and streams the Response back to the Go ResponseWriter.\n\nThe handlerFunc parameter is the name of the JavaScript handler function to call. The options parameter specifies additional configuration, such as the context to run the handler in.\n\nThe handler function should accept a Request object (compatible with the Fetch API) and must return a Response object (also compatible with the Fetch API). For example:\n\n\t// In JavaScript:\n\tmyHandler = function(request) {\n\t  return new Response(JSON.stringify({hello: 'world'}), {\n\t    status: 200,\n\t    headers: {'Content-Type': 'application/json'}\n\t  });\n\t}\n\nIf an error occurs in the JavaScript handler, it will be logged and a 500 Internal Server Error will be returned, unless headers have already been written to the response.\n\n```go\nfunc (p *Process) Set(v string, val any)\n```\nSet sets a variable in the javascript global scope of this instance\n\n```go\nfunc (p *Process) SetContext(ctx context.Context)\n```\n\n```go\nfunc (p *Process) SetIPC(name string, f IpcFunc)\n```\nSetIPC adds an IPC that can be called from nodejs\n\n","path":"github.com/KarpelesLab/nodejs","name":"nodejs","synopsis":"","isRedistributable":true}
