49 lines
1.5 KiB
Go
49 lines
1.5 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 given " + u.String(len(args.Arguments))))
|
||
|
}
|
||
|
if r, err := u.ReadFile(u.String(args.Arguments[0].Export())); err == nil {
|
||
|
return vm.ToValue(r)
|
||
|
} else {
|
||
|
return 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 given " + u.String(len(args.Arguments))))
|
||
|
}
|
||
|
if err := u.WriteFileBytes(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 given " + u.String(len(args.Arguments))))
|
||
|
}
|
||
|
if r, err := u.ReadDir(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 given " + u.String(len(args.Arguments))))
|
||
|
}
|
||
|
return vm.ToValue(u.GetFileInfo(u.String(args.Arguments[0].Export())))
|
||
|
},
|
||
|
}
|
||
|
}
|