Argument | Description | Types / Required |
path | The path of the file to read. | string
required |
encoding | The encoding to use to decode the file's text.
The default value is "UTF-8". | string
not required |
The
File.readLines action reads a file, specified as
path, as text, returning the entire file's content as an array of strings. The file's content is split on newline characters, with each line returned as an element of the array without the newline character included.
The
encoding argument allows you specify how the contents of the file are
decoded to text. There are few cases where this may be necessary, as the default of reading UTF-8 text will generally meet the needs of most users. Options include:
- "ANSI": The contents are decoded as part of the Windows code page.
- "UTF-8": The contents are decoded as UTF-8, regardless of whether there is a byte order mark (BOM).
- "UTF-8-BOM": The contents are decoded as UTF-8, regardless of whether there is a BOM.
The action returns an array of strings containing the file's content, with each line as an entry in the array.
The action throws an exception if any of its arguments are not specified in a valid form or if the file does not exist or cannot be read.
// read all the lines from a file
CS.File.readLinesAsync({
path: "text-file.txt"
})
.then(lines => {
// remove whitespace from the end of each line
const trimmedLines = lines.map(line => line.trimEnd());
// write the lines
return CS.File.writeLinesAsync({
path: "text-file (trimmed).txt",
lines: trimmedLines
});
})
.then(() => console.log("Successfully read, trimmed, and wrote the lines."))
.catch(error => console.log(error));