github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/io/fs/read.go (about)

     1  package fs
     2  
     3  import (
     4  	"context"
     5  	"io/ioutil"
     6  
     7  	"github.com/MontFerret/ferret/pkg/runtime/core"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values"
     9  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
    10  )
    11  
    12  // READ reads from a given file.
    13  // @param {String} path - Path to file to read from.
    14  // @return {Binary} - File content in binary format.
    15  func Read(_ context.Context, args ...core.Value) (core.Value, error) {
    16  	err := core.ValidateArgs(args, 1, 1)
    17  
    18  	if err != nil {
    19  		return values.None, core.Error(err, "validate arguments number")
    20  	}
    21  
    22  	err = core.ValidateType(args[0], types.String)
    23  
    24  	if err != nil {
    25  		return values.None, core.Error(err, "validate [0] argument")
    26  	}
    27  
    28  	path := args[0].String()
    29  
    30  	data, err := ioutil.ReadFile(path)
    31  
    32  	if err != nil {
    33  		return values.None, core.Error(err, "read file")
    34  	}
    35  
    36  	return values.NewBinary(data), nil
    37  }