51 lines
1.6 KiB
Go
51 lines
1.6 KiB
Go
package js
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"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(u.String(args.Arguments[0].Export())); err == nil {
|
|
return vm.ToValue(r)
|
|
} else {
|
|
fmt.Println(err, "-----")
|
|
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, but 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, but 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, but given " + u.String(len(args.Arguments))))
|
|
}
|
|
return vm.ToValue(u.GetFileInfo(u.String(args.Arguments[0].Export())))
|
|
},
|
|
}
|
|
}
|