Best K6 code snippet using js.requireModule
resolve.go
Source:resolve.go  
1package require2import (3	"encoding/json"4	"errors"5	"path"6	"strings"7	js "github.com/dop251/goja"8)9// NodeJS module search algorithm described by10// https://nodejs.org/api/modules.html#modules_all_together11func (r *RequireModule) resolve(modpath string) (module *js.Object, err error) {12	origPath, modpath := modpath, filepathClean(modpath)13	if modpath == "" {14		return nil, IllegalModuleNameError15	}16	module, err = r.loadNative(modpath)17	if err == nil {18		return19	}20	var start string21	err = nil22	if path.IsAbs(origPath) {23		start = "/"24	} else {25		start = r.getCurrentModulePath()26	}27	p := path.Join(start, modpath)28	if strings.HasPrefix(origPath, "./") ||29		strings.HasPrefix(origPath, "/") || strings.HasPrefix(origPath, "../") ||30		origPath == "." || origPath == ".." {31		if module = r.modules[p]; module != nil {32			return33		}34		module, err = r.loadAsFileOrDirectory(p)35		if err == nil && module != nil {36			r.modules[p] = module37		}38	} else {39		if module = r.nodeModules[p]; module != nil {40			return41		}42		module, err = r.loadNodeModules(modpath, start)43		if err == nil && module != nil {44			r.nodeModules[p] = module45		}46	}47	if module == nil && err == nil {48		err = InvalidModuleError49	}50	return51}52func (r *RequireModule) loadNative(path string) (*js.Object, error) {53	module := r.modules[path]54	if module != nil {55		return module, nil56	}57	var ldr ModuleLoader58	if ldr = r.r.native[path]; ldr == nil {59		ldr = native[path]60	}61	if ldr != nil {62		module = r.createModuleObject()63		r.modules[path] = module64		ldr(r.runtime, module)65		return module, nil66	}67	return nil, InvalidModuleError68}69func (r *RequireModule) loadAsFileOrDirectory(path string) (module *js.Object, err error) {70	if module, err = r.loadAsFile(path); module != nil || err != nil {71		return72	}73	return r.loadAsDirectory(path)74}75func (r *RequireModule) loadAsFile(path string) (module *js.Object, err error) {76	if module, err = r.loadModule(path); module != nil || err != nil {77		return78	}79	p := path + ".js"80	if module, err = r.loadModule(p); module != nil || err != nil {81		return82	}83	p = path + ".json"84	return r.loadModule(p)85}86func (r *RequireModule) loadIndex(modpath string) (module *js.Object, err error) {87	p := path.Join(modpath, "index.js")88	if module, err = r.loadModule(p); module != nil || err != nil {89		return90	}91	p = path.Join(modpath, "index.json")92	return r.loadModule(p)93}94func (r *RequireModule) loadAsDirectory(modpath string) (module *js.Object, err error) {95	p := path.Join(modpath, "package.json")96	buf, err := r.r.getSource(p)97	if err != nil {98		return r.loadIndex(modpath)99	}100	var pkg struct {101		Main string102	}103	err = json.Unmarshal(buf, &pkg)104	if err != nil || len(pkg.Main) == 0 {105		return r.loadIndex(modpath)106	}107	m := path.Join(modpath, pkg.Main)108	if module, err = r.loadAsFile(m); module != nil || err != nil {109		return110	}111	return r.loadIndex(m)112}113func (r *RequireModule) loadNodeModule(modpath, start string) (*js.Object, error) {114	return r.loadAsFileOrDirectory(path.Join(start, modpath))115}116func (r *RequireModule) loadNodeModules(modpath, start string) (module *js.Object, err error) {117	for _, dir := range r.r.globalFolders {118		if module, err = r.loadNodeModule(modpath, dir); module != nil || err != nil {119			return120		}121	}122	for {123		var p string124		if path.Base(start) != "node_modules" {125			p = path.Join(start, "node_modules")126		} else {127			p = start128		}129		if module, err = r.loadNodeModule(modpath, p); module != nil || err != nil {130			return131		}132		if start == ".." { // Dir('..') is '.'133			break134		}135		parent := path.Dir(start)136		if parent == start {137			break138		}139		start = parent140	}141	return nil, InvalidModuleError142}143func (r *RequireModule) getCurrentModulePath() string {144	var buf [2]js.StackFrame145	frames := r.runtime.CaptureCallStack(2, buf[:0])146	if len(frames) < 2 {147		return "."148	}149	return path.Dir(frames[1].SrcName())150}151func (r *RequireModule) createModuleObject() *js.Object {152	module := r.runtime.NewObject()153	module.Set("exports", r.runtime.NewObject())154	return module155}156func (r *RequireModule) loadModule(path string) (*js.Object, error) {157	module := r.modules[path]158	if module == nil {159		module = r.createModuleObject()160		r.modules[path] = module161		err := r.loadModuleFile(path, module)162		if err != nil {163			module = nil164			delete(r.modules, path)165			if errors.Is(err, ModuleFileDoesNotExistError) {166				err = nil167			}168		}169		return module, err170	}171	return module, nil172}173func (r *RequireModule) loadModuleFile(path string, jsModule *js.Object) error {174	prg, err := r.r.getCompiledSource(path)175	if err != nil {176		return err177	}178	f, err := r.runtime.RunProgram(prg)179	if err != nil {180		return err181	}182	if call, ok := js.AssertFunction(f); ok {183		jsExports := jsModule.Get("exports")184		jsRequire := r.runtime.Get("require")185		// Run the module source, with "jsExports" as "this",186		// "jsExports" as the "exports" variable, "jsRequire"187		// as the "require" variable and "jsModule" as the188		// "module" variable (Nodejs capable).189		_, err = call(jsExports, jsExports, jsRequire, jsModule)190		if err != nil {191			return err192		}193	} else {194		return InvalidModuleError195	}196	return nil197}...module.go
Source:module.go  
1package require2import (3	js "github.com/dop251/goja"4	"errors"5	"fmt"6	"io/ioutil"7	"path/filepath"8	"sync"9)10type ModuleLoader func(*js.Runtime, *js.Object)11type SourceLoader func(path string) ([]byte, error)12var (13	InvalidModuleError     = errors.New("Invalid module")14	IllegalModuleNameError = errors.New("Illegal module name")15)16var native map[string]ModuleLoader17// Registry contains a cache of compiled modules which can be used by multiple Runtimes18type Registry struct {19	sync.Mutex20	compiled map[string]*js.Program21	srcLoader SourceLoader22}23type RequireModule struct {24	r       *Registry25	runtime *js.Runtime26	modules map[string]*js.Object27}28func NewRegistryWithLoader(srcLoader SourceLoader) *Registry {29	return &Registry{30		srcLoader: srcLoader,31	}32}33// Enable adds the require() function to the specified runtime.34func (r *Registry) Enable(runtime *js.Runtime) *RequireModule {35	rrt := &RequireModule{36		r:       r,37		runtime: runtime,38		modules: make(map[string]*js.Object),39	}40	runtime.Set("require", rrt.require)41	runtime.Set("require_list", rrt.list)42	runtime.Set("require_set", rrt.set)43	runtime.Set("require_get", rrt.get)44	return rrt45}46func (r *Registry) getCompiledSource(p string) (prg *js.Program, err error) {47	r.Lock()48	defer r.Unlock()49	prg = r.compiled[p]50	if prg == nil {51		srcLoader := r.srcLoader52		if srcLoader == nil {53			srcLoader = ioutil.ReadFile54		}55		if s, err1 := srcLoader(p); err1 == nil {56			source := "(function(module, exports) {" + string(s) + "\n})"57			prg, err = js.Compile(p, source, false)58			if err == nil {59				if r.compiled == nil {60					r.compiled = make(map[string]*js.Program)61				}62				r.compiled[p] = prg63			}64		} else {65			err = err166		}67	}68	return69}70func (r *RequireModule) loadModule(path string, jsModule *js.Object) error {71	if ldr, exists := native[path]; exists {72		ldr(r.runtime, jsModule)73		return nil74	}75	prg, err := r.r.getCompiledSource(path)76	if err != nil {77		return err78	}79	f, err := r.runtime.RunProgram(prg)80	if err != nil {81		return err82	}83	if call, ok := js.AssertFunction(f); ok {84		jsExports := jsModule.Get("exports")85		// Run the module source, with "jsModule" as the "module" variable, "jsExports" as "this"(Nodejs capable).86		_, err = call(jsExports, jsModule, jsExports)87		if err != nil {88			return err89		}90	} else {91		return InvalidModuleError92	}93	return nil94}95func (r *RequireModule) list(call js.FunctionCall) js.Value {96	return r.runtime.ToValue(r.modules)97}98func (r *RequireModule) set(call js.FunctionCall) js.Value {99	key := call.Argument(0).String()100	value := call.Argument(1).ToObject(r.runtime)101	r.modules[key] = value102	return nil103}104func (r *RequireModule) get(call js.FunctionCall) js.Value {105	key := call.Argument(0).String()106	if v, ok := r.modules[key]; ok {107		return r.runtime.ToValue(v)108	}109	return nil110}111func (r *RequireModule) require(call js.FunctionCall) js.Value {112	ret, err := r.Require(call.Argument(0).String())113	if err != nil {114		panic(r.runtime.NewGoError(err))115	}116	return ret117}118func filepathClean(p string) string {119	return filepath.Clean(p)120}121// Require can be used to import modules from Go source (similar to JS require() function).122func (r *RequireModule) Require(p string) (ret js.Value, err error) {123	p = filepathClean(p)124	if p == "" {125		err = IllegalModuleNameError126		return127	}128	module := r.modules[p]129	if module == nil {130		module = r.runtime.NewObject()131		module.Set("exports", r.runtime.NewObject())132		r.modules[p] = module133		err = r.loadModule(p, module)134		if err != nil {135			delete(r.modules, p)136			err = fmt.Errorf("Could not load module '%s': %v", p, err)137			return138		}139	}140	ret = module.Get("exports")141	return142}143func Require(runtime *js.Runtime, name string) js.Value {144	if r, ok := js.AssertFunction(runtime.Get("require")); ok {145		mod, err := r(js.Undefined(), runtime.ToValue(name))146		if err != nil {147			panic(err)148		}149		return mod150	}151	panic(runtime.NewTypeError("Please enable require for this runtime using new(require.Require).Enable(runtime)"))152}153func RegisterNativeModule(name string, loader ModuleLoader) {154	if native == nil {155		native = make(map[string]ModuleLoader)156	}157	name = filepathClean(name)158	native[name] = loader159}...requireModule
Using AI Code Generation
1import (2func main() {3	global := js.Global()4	require := global.Get("require")5	require.Invoke("fs", js.FuncOf(func(this js.Value, args []js.Value) interface{} {6		data := fs.Call("readFileSync", "1.js")7		println(data.String())8	}))9	select {}10}11import (12func main() {13	global := js.Global()14	require := global.Get("require")15	require.Invoke("2.js", js.FuncOf(func(this js.Value, args []js.Value) interface{} {16		exports.Invoke("Hello World")17	}))18	select {}19}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
