text
The text
utility makes it easier to read and write to any file within in your checks.
This utility expects an absolute path to a JSON file and returns an object with methods that help you read and write to any file.
import { json } from 'commonality';
const readme = text('/path/from/root/README.md');
exists
() => Promise<boolean>
Returns a boolean value indicating whether or not the file exists on disk.
Example
const exists = await text('/path/from/root/README.md').exists();
console.log(exists);
// true
get
() => Promise<string[] | undefined>
Returns
Returns the contents of a file as an array of strings representing each line. If the file does not exist, undefined
will be returned.
Example
const readme = await text('/path/from/root/README.md').get();
console.log(readme);
// [
// '# My Package',
// '',
// 'This is my package',
// ]
contains
(value: string[]) => Promise<boolean>
Parameters
An array of strings, representing lines of text.
Returns
Returns a boolean value indicating whether specified lines exist in the file. If the file does not exist, false
will be returned.
Example
const containsLines = await text('.npmignore').contains([
'dist',
]);
console.log(containsLines);
// true
set
(lines: string[]) => Promise<void>
Overwrites the entire contents of a file with the provided lines of text. If the file does not exist, it will be created.
Parameters
An array of strings, representing lines of text.
Example
await text('/path/from/root/README.md').set([
'# My Package',
'',
'This is my package',
]);
remove
(lines: string[]) => Promise<void>
Removes lines of text from a file, if they exist. Lines of text that are not included in the array will not be affected.
Parameters
An array of strings, representing lines of text.
Example
await text('/path/from/root/README.md').remove(['# My Package']);
delete
() => Promise<void>
Deletes a file from disk.
Example
await text('/path/from/root/README.md').delete();