file/file.go

117 lines
3.1 KiB
Go
Raw Permalink Normal View History

2024-10-11 12:02:48 +08:00
package file
import (
_ "embed"
"os"
"apigo.cc/gojs"
"apigo.cc/gojs/goja"
"github.com/ssgo/u"
)
//go:embed file.ts
var fileTS string
//go:embed README.md
var fileMD string
func init() {
obj := map[string]any{
"read": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
if r, err := u.ReadFile(args.Path(0)); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"readBytes": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
if r, err := u.ReadFileBytes(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 := gojs.MakeArgs(&argsIn, vm).Check(2)
if err := u.WriteFileBytes(args.Path(0), args.Bytes(1)); err == nil {
return nil
} else {
panic(vm.NewGoError(err))
}
},
"dir": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.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 := gojs.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 := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(args.Path(0))
},
"remove": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
if err := os.RemoveAll(args.Path(0)); err == nil {
return nil
} else {
panic(vm.NewGoError(err))
}
},
"rename": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2)
if err := os.Rename(args.Path(0), args.Path(1)); err == nil {
return nil
} else {
panic(vm.NewGoError(err))
}
},
"copy": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2)
if err := u.CopyFile(args.Path(0), args.Path(1)); err == nil {
return nil
} else {
panic(vm.NewGoError(err))
}
},
"cache": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
compress := args.Bool(1)
if compress {
u.LoadFileToMemoryWithCompress(args.Path(0))
} else {
u.LoadFileToMemory(args.Path(0))
}
return nil
},
}
gojs.Register("apigo.cc/gojs/file", gojs.Module{
Object: obj,
Desc: "file api by https://github.com/ssgo/u",
TsCode: fileTS,
Example: fileMD,
})
}
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(),
}
}