x
This commit is contained in:
+30
-11
@@ -1,14 +1,18 @@
|
|||||||
package core
|
package core
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"errors"
|
"errors"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
|
||||||
iconv "github.com/djimenez/iconv-go"
|
|
||||||
"github.com/dop251/goja"
|
"github.com/dop251/goja"
|
||||||
|
"golang.org/x/net/html/charset"
|
||||||
|
"golang.org/x/text/encoding/ianaindex"
|
||||||
|
"golang.org/x/text/transform"
|
||||||
)
|
)
|
||||||
|
|
||||||
func getJsOs(vm *goja.Runtime, running func() bool) *goja.Object {
|
func getJsOs(vm *goja.Runtime, running func() bool) *goja.Object {
|
||||||
@@ -21,29 +25,44 @@ func getJsOs(vm *goja.Runtime, running func() bool) *goja.Object {
|
|||||||
return data
|
return data
|
||||||
})
|
})
|
||||||
jsos.Set("readFileSync", func(path string) string {
|
jsos.Set("readFileSync", func(path string) string {
|
||||||
content, err := ioutil.ReadFile(path)
|
// 读取文件内容
|
||||||
|
content, err := ioutil.ReadFile("example.txt")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(Error(vm, err))
|
panic(Error(vm, err))
|
||||||
}
|
}
|
||||||
// 自动转换编码为UTF-8
|
|
||||||
utf8Content, err := iconv.ConvertString(string(content), "auto", "utf-8")
|
// 从文件内容中自动检测编码
|
||||||
|
encoding, _, _ := charset.DetermineEncoding(content, "")
|
||||||
|
|
||||||
|
// 创建一个将编码转换为 UTF-8 的转换器
|
||||||
|
utf8Reader := transform.NewReader(bytes.NewReader(content), encoding.NewDecoder())
|
||||||
|
|
||||||
|
// 读取转换后的 UTF-8 数据
|
||||||
|
utf8Content, err := ioutil.ReadAll(utf8Reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(Error(vm, err))
|
panic(Error(vm, err))
|
||||||
}
|
}
|
||||||
return utf8Content
|
return string(utf8Content)
|
||||||
})
|
})
|
||||||
|
|
||||||
jsos.Set("writeFileSync", func(path, content string, encode string) {
|
jsos.Set("writeFileSync", func(path, content string, encode string) {
|
||||||
// 将文本内容转换为GBK编码
|
|
||||||
var err error
|
encode = strings.ToLower(encode)
|
||||||
if !(encode == "" || encode == "utf-8") {
|
if encode == "" {
|
||||||
content, err = iconv.ConvertString(content, "utf-8", encode)
|
encode = "utf-8"
|
||||||
|
}
|
||||||
|
// 将UTF-8编码的文本转换为指定编码
|
||||||
|
index := ianaindex.MIME
|
||||||
|
enc, err := index.Encoding(encode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(Error(vm, err))
|
panic(Error(vm, err))
|
||||||
}
|
}
|
||||||
|
converted, _, err := transform.String(enc.NewEncoder(), content)
|
||||||
|
if err != nil {
|
||||||
|
panic(Error(vm, err))
|
||||||
}
|
}
|
||||||
// 将文本内容以GBK编码写入文件
|
// 覆盖写入文件
|
||||||
err = ioutil.WriteFile(path, []byte(content), 0644)
|
err = os.WriteFile(path, []byte(converted), 0644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(Error(vm, err))
|
panic(Error(vm, err))
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user