Debian Codegraph @

js/fs.go

raw symbols SCIP
1 package js
2
3 import (
4 "github.com/robertkrimen/otto"
5 "io/ioutil"
6 )
7
8 func readDir(call otto.FunctionCall) otto.Value {
9 argv := call.ArgumentList
10 argc := len(argv)
11 if argc != 1 {
12 return ReportError("readDir: expected 1 argument, %d given instead.", argc)
13 }
14
15 path := argv[0].String()
16 dir, err := ioutil.ReadDir(path)
17 if err != nil {
18 return ReportError("Could not read directory %s: %s", path, err)
19 }
20
21 entry_list := []string{}
22 for _, file := range dir {
23 entry_list = append(entry_list, file.Name())
24 }
25
26 v, err := otto.Otto.ToValue(*call.Otto, entry_list)
27 if err != nil {
28 return ReportError("Could not convert to array: %s", err)
29 }
30
31 return v
32 }
33
34 func readFile(call otto.FunctionCall) otto.Value {
35 argv := call.ArgumentList
36 argc := len(argv)
37 if argc != 1 {
38 return ReportError("readFile: expected 1 argument, %d given instead.", argc)
39 }
40
41 filename := argv[0].String()
42 raw, err := ioutil.ReadFile(filename)
43 if err != nil {
44 return ReportError("Could not read file %s: %s", filename, err)
45 }
46
47 v, err := otto.ToValue(string(raw))
48 if err != nil {
49 return ReportError("Could not convert to string: %s", err)
50 }
51 return v
52 }
53
54 func writeFile(call otto.FunctionCall) otto.Value {
55 argv := call.ArgumentList
56 argc := len(argv)
57 if argc != 2 {
58 return ReportError("writeFile: expected 2 arguments, %d given instead.", argc)
59 }
60
61 filename := argv[0].String()
62 data := argv[1].String()
63
64 err := ioutil.WriteFile(filename, []byte(data), 0644)
65 if err != nil {
66 return ReportError("Could not write %d bytes to %s: %s", len(data), filename, err)
67 }
68
69 return otto.NullValue()
70 }