ai_old/js/file.go
Star e69b9a3a12 add db、log support
support embedding for llm
support watch run for js
many other updates
2024-09-29 21:20:28 +08:00

75 lines
2.0 KiB
Go

package js
import (
"apigo.cc/ai/ai/goja"
"github.com/ssgo/u"
"os"
)
func RequireFile() map[string]any {
return map[string]any{
"read": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := MakeArgs(&argsIn, vm).Check(1)
if r, err := u.ReadFile(args.Path(0)); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"write": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := MakeArgs(&argsIn, vm).Check(2)
if err := u.WriteFileBytes(args.Path(0), u.Bytes(args.Any(0))); err == nil {
return nil
} else {
panic(vm.NewGoError(err))
}
},
"dir": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := MakeArgs(&argsIn, vm).Check(1)
if r, err := u.ReadDir(args.Path(0)); err == nil {
list := make([]map[string]any, len(r))
for i, info := range r {
list[i] = makeFileInfo(&info)
}
return vm.ToValue(list)
} else {
panic(vm.NewGoError(err))
}
},
"stat": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(makeFileInfo(u.GetFileInfo(args.Path(0))))
},
"find": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(args.Path(0))
},
"remove": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := MakeArgs(&argsIn, vm).Check(1)
if err := os.RemoveAll(args.Path(0)); err == nil {
return nil
} else {
panic(vm.NewGoError(err))
}
},
"copy": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := MakeArgs(&argsIn, vm).Check(2)
if err := u.CopyFile(args.Path(0), args.Path(1)); err == nil {
return nil
} else {
panic(vm.NewGoError(err))
}
},
}
}
func makeFileInfo(info *u.FileInfo) map[string]any {
return map[string]any{
"name": info.Name,
"size": info.Size,
"fullName": info.FullName,
"isDir": info.IsDir,
"modTime": info.ModTime.UnixMilli(),
}
}