55 lines
1.9 KiB
Go
55 lines
1.9 KiB
Go
package js
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/dop251/goja"
|
|
"github.com/ssgo/u"
|
|
)
|
|
|
|
func RequireFile() map[string]any {
|
|
return map[string]any{
|
|
"read": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
|
|
if len(args.Arguments) < 1 {
|
|
return vm.NewGoError(errors.New("arguments need 1, but given " + u.String(len(args.Arguments))))
|
|
}
|
|
if r, err := u.ReadFile(findPath(vm, u.String(args.Arguments[0].Export()))); err == nil {
|
|
return vm.ToValue(r)
|
|
} else {
|
|
panic(vm.NewGoError(err))
|
|
}
|
|
},
|
|
"write": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
|
|
if len(args.Arguments) < 2 {
|
|
return vm.NewGoError(errors.New("arguments need 2, but given " + u.String(len(args.Arguments))))
|
|
}
|
|
if err := u.WriteFileBytes(findPath(vm, u.String(args.Arguments[0].Export())), u.Bytes(args.Arguments[0].Export())); err == nil {
|
|
return nil
|
|
} else {
|
|
return vm.NewGoError(err)
|
|
}
|
|
},
|
|
"dir": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
|
|
if len(args.Arguments) < 1 {
|
|
return vm.NewGoError(errors.New("arguments need 1, but given " + u.String(len(args.Arguments))))
|
|
}
|
|
if r, err := u.ReadDir(findPath(vm, u.String(args.Arguments[0].Export()))); err == nil {
|
|
return vm.ToValue(r)
|
|
} else {
|
|
return vm.NewGoError(err)
|
|
}
|
|
},
|
|
"stat": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
|
|
if len(args.Arguments) < 1 {
|
|
return vm.NewGoError(errors.New("arguments need 1, but given " + u.String(len(args.Arguments))))
|
|
}
|
|
return vm.ToValue(u.GetFileInfo(findPath(vm, u.String(args.Arguments[0].Export()))))
|
|
},
|
|
"find": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
|
|
if len(args.Arguments) < 1 {
|
|
return vm.NewGoError(errors.New("arguments need 1, but given " + u.String(len(args.Arguments))))
|
|
}
|
|
return vm.ToValue(findPath(vm, u.String(args.Arguments[0].Export())))
|
|
},
|
|
}
|
|
}
|