File

Overview

File objects represent a file on the file system, whether it exists or not, based on its path.

To get or create File objects, you can:

To check if a given Item object is a File, you can use the instanceof operator.

Methods and properties

Getting an instance from an absolute path

File File(String absolutePath)

Returns a new File instance for absolutePath.
On Windows, the path can optionally include a drive identifier.
absolutePath
The absolute path to the file to get.
sample Get a folder by absolute path
const fonts = Folder('/System/Library/Fonts/');
sample Get a file on a specific Windows drive
const directXLog = File('C:/Windows/DirectX.log');

Creating, deleting, checking existence and comparing

exists Boolean

Whether or not the file exists on disk.
If there is an item of the same name which isn't a file, returns false.
Read-only.
sample Check if a file exists
let newFile = here.file('new-file.txt');

cli.tell(newFile.exists); // `false`

newFile.make();
cli.tell(newFile.exists); // now `true`

self make([Boolean forgiving])

Creates the file based on its path.
Throws if the parent doesn't exist, or if there is already an item at that path.
forgiving
If true:
  • If the parent doesn't exist, make() doesn't throw and creates the parent folder and any missing parent folder.
  • If there is already an item of the same name, only throws if the item is not a file. If it is a file, does not modify it.
Defaults to false.
sample Create a file
let newFile = here.file('new-file.txt');
newFile.make();

cli.tell(newFile.exists); // now `true`
sample Create a file and its parents
let packageFolder = here.folder('new-package/');
let packageMetadata = here.file('new-package/package.json');

cli.tell(packageFolder.exists); // `false`
cli.tell(packageMetadata.exists); // `false`

packageMetadata.make(true);

cli.tell(packageFolder.exists); // `true`
cli.tell(packageMetadata.exists); // `true`

File copyTo(Folder destination, [Boolean forgiving])

Copies the file into the destination folder, and returns a File object representing the copy.
Throws if there already exists an item of the same name at the destination, or if the destination doesn't exist.
destination
The folder in which to create the copy.
forgiving
If true, if destination doesn't exist, copyTo() doesn't throw and creates destination and any missing parent folder.
Defaults to false.
sample Copy a file and give the copy a new name
const playerSheetTemplate = here.file('templates/player-sheet.template.md');

let newPlayerSheet = playerSheetTemplate.copyTo(here);
newPlayerSheet.name = 'player-sheet.md';

File duplicate([String newName])

Creates a copy of the file in the same folder, and returns a File object representing the copy. The name of the copy is derived from the file's name.
newName
The name to use for the copy instead of an automatically-picked one. duplicate() will throw if the name is taken.
sample Duplicate a file then move the copy somewhere else
const playerSheetTemplate = here.file('templates/player-sheet.template.md');

let newPlayerSheet = playerSheetTemplate.duplicate('player-sheet.md');
newPlayerSheet.moveTo(here);

self delete([Boolean immediately])

Deletes the file by moving it to the user's trash.
Implemented using the trash package.
immediately
If true, the file is deleted right away instead of being placed in the trash.
Defaults to false.
sample Clean up after an operation
const keepLog = await cli.ask('Keep log file?', Boolean);
if (!keepLog) here.file('events.log').delete();

Boolean equals(Item other)

Returns true if item is the same (is also a file, and has the same path).
other
The item to compare with.
sample Ask for two different folders
const sourceFolder = await cli.ask('From?', Folder);
const destinationFolder = await cli.ask('To?', [Folder, function(value) {
		if (value.equals(sourceFolder)) {
			throw 'is the same as the source';
		}
		return value;
	}
]);

cli.tell('Will copy from: ' + sourceFolder.name);
cli.tell('Will copy to: ' + destinationFolder.name);

Name and path

name String

The complete name of the file, including its extension.
sample Display the name of the first found log file
const someLog = logFolder.children[0];
cli.tell(someLog.name); // "events.log"

bareName String

The name of the file, without the extension.
sample Get the bareName of a file
const readme = here.file('README.md');
cli.tell(readme.bareName); // "README"

const minifiedMomentFile = here.file('moment.min.js');
cli.tell(minifiedMomentFile.bareName); // "moment.min"
sample Set the bareName of a file
const readme = here.file('README.md');
readme.bareName = 'First steps';
cli.tell(readme.name); // "First steps.md"

extension String

The extension of the file, such as "txt".

path String

The absolute path to the file, including its name.
sample Read the path of a folder
cli.tell(home.path); // something like "/Users/cykelero/"

parent Folder

The parent Folder of the file.
Is null if the item is a file system root.
sample Get the parent of the user folder
const userFolderParent = home.parent;
cli.tell(userFolderParent.path);

self moveTo(Folder destination, [Boolean forgiving])

Moves the file into the destination folder.
Throws if there already exists an item of the same name at the destination, or if the destination doesn't exist.
destination
The new parent folder.
forgiving
If true, if destination doesn't exist, moveTo() doesn't throw and creates destination and any missing parent folder.
Defaults to false.
sample Move a file
const folderA = here.folder('A/');
const folderB = here.folder('B/');
let file = folderA.file('file.txt');

cli.tell(file.parent.name); // "A"

file.moveTo(folderB);
cli.tell(file.parent.name); // "B"

Metadata

dateCreated Moment

The creation date of the file. Only supported on macOS.

dateModified Moment

The last modification date of the file.

user ItemUserPermissions

The ItemUserPermissions object for the file. Allows reading and modifying the owner of the file, and the owner's permissions to the file.
Read-only.
sample Make a file user-executable
const script = here.file('script.js');
script.user.canExecute = true;

group ItemGroupPermissions

The ItemGroupPermissions object for the file. Allows reading and modifying the owner group of the file, and the group's permissions to the file.
Read-only.
sample Make a file group-writeable
const script = here.file('script.js');
script.group.canWrite = true;

other ItemOtherPermissions

The ItemOtherPermissions object for the file. Allows reading and modifying world permissions to the file.
Read-only.
sample Make a file world-readable
const script = here.file('script.js');
script.other.canRead = true;

Contents

content String

The text content of the file, interpreted as UTF-8.
When set, the value is serialized using JSON.stringify() if it isn't already a string.
Throws if the file doesn't exist.
sample Count the lines in a text file
const readmeContent = here.file('README.md').content;
const readmeLineCount = readmeContent.split('\n').length;
cli.tell(`The readme file has ${format.number.integer(readmeLineCount, 'line')}.`);
sample Write JSON to a file
const basicInfo = {
	name: await cli.ask('Project name?'),
	description: await cli.ask('Project description?')
};

here.file('package.json').make().content = basicInfo;

Any getContentAs(TypeDefinition castType)

Reads the text content of the file, then casts it using castType and returns the result.
If the content of the file is not valid for castType, the method returns null instead.
Throws if the file doesn't exist.
castType
The type definition to apply to the text content.
sample Read a date from a file
const lastUpdateDate = here.file('lastUpdateDate.txt').getContentAs(Date);
cli.tell('Last update: ' + format.date.relative(lastUpdateDate));

Any getContentAsJSON()

Reads the text content of the file, then parses it as JSON and returns the result.
If the content of the file is not valid JSON, the method returns null instead.
Throws if the file doesn't exist.
sample Read JSON from a file
const packageInfo = here.file('package.json').getContentAsJSON();
cli.tell(`The current project is ${packageInfo.name}.`);

md5 String

The md5 checksum of the file.
Read-only.
sample Compare the content of two files
const fileA = await cli.ask('First file?', File);
const fileB = await cli.ask('Second file?', File);

const contentIdentical = fileA.md5 === fileB.md5;

cli.tell('The two files are ' + (contentIdentical ? 'the same' : 'different') + '.');

size Number

The size of the file, in bytes.
Read-only.

self appendLine(Any content, Boolean forgiving)

Serializes content using JSON.stringify() if it is not already a string, then adds it at the end of the file, followed by a newline character.
Throws if the file doesn't exist.
content
The content to be appended.
forgiving
If true, if the file doesn't exist, appendLine() doesn't throw and creates the file.
The method will still throw if the parent doesn't exist.
sample Add text at the end of a file
here.file('events.log').appendLine('Operation complete.');

self prependLine(Any content, Boolean forgiving)

Serializes content using JSON.stringify() if it is not already a string, then adds it at the beginning of the file, followed by a newline character.
Throws if the file doesn't exist.
content
The content to be prepended.
forgiving
If true, if the file doesn't exist, appendLine() doesn't throw and creates the file.
The method will still throw if the parent doesn't exist.
sample Add text at the beginning of a file
here.file('events.log').prependLine('Operation complete.');

self clear(Boolean forgiving)

Empties the file, removing all its content.
Throws if the file doesn't exist.
forgiving
If true, if the file doesn't exist, clear() doesn't throw and creates the file.
The method will still throw if the parent doesn't exist.
Defaults to false.
sample Make sure a file exists and is empty
const projectFolder = await cli.ask('Where should the project be initialized?', Folder);
projectFolder.file('package.json').clear(true);

Setting multiple properties at once

self set(Object values)

For each key-value couple in values, sets the key attribute of the File to value. This makes it easy to set multiple attributes on the object at once.
values
A map of property names and values.
sample Move and rename a file in one call
let packageInfo = here.file('package.json');
packageInfo.set({
	name: 'package-previous',
	parent: here.folder('archive/')
});

return packageInfo.name; // returns `'package-previous'`