diff --git a/README.md b/README.md index cd470bc..32fbbf6 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,11 @@ # xk6-file -A [k6](https://github.com/loadimpact/k6) extension for writing files, implemented using the +[k6](https://github.com/loadimpact/k6) extension for writing files, implemented using the [xk6](https://github.com/k6io/xk6) system. ## Build -`xk6 build v0.31.1 --with github.com/avitalique/xk6-file` +```shell +xk6 build v0.31.1 --with github.com/avitalique/xk6-file +``` ## Example ```javascript @@ -12,6 +14,7 @@ import file from 'k6/x/file'; const filepath = 'sample-output.txt'; export default function () { - file.appendString(filepath, `Some text. VU: ${__VU} - ITER: ${__ITER}\n`); + file.writeString(filepath, 'New file. First line.\n'); + file.appendString(filepath, `Second line. VU: ${__VU} - ITER: ${__ITER}`); } ``` \ No newline at end of file diff --git a/file.go b/file.go index 66d723d..e02fb88 100644 --- a/file.go +++ b/file.go @@ -14,10 +14,24 @@ func init() { modules.Register("k6/x/file", new(FILE)) } -// FILE is the k6 extension. +// FILE is the k6 extension type FILE struct{} -// Append a string to file +// Write string to file +func (*FILE) WriteString(path string, s string) error { + f, err := os.Create(path) + if err != nil { + return err + } + defer f.Close() + + if _, err := f.WriteString(s); err != nil { + return err + } + return nil +} + +// Append string to file func (*FILE) AppendString(path string, s string) error { f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) diff --git a/sample-script.js b/sample-script.js index 3c87286..8bcf90d 100644 --- a/sample-script.js +++ b/sample-script.js @@ -3,5 +3,6 @@ import file from 'k6/x/file'; const filepath = 'sample-output.txt'; export default function () { - file.appendString(filepath, `Some text. VU: ${__VU} - ITER: ${__ITER}\n`); + file.writeString(filepath, 'New file. First line.\n'); + file.appendString(filepath, `Second line. VU: ${__VU} - ITER: ${__ITER}`); } \ No newline at end of file