Comprehensive file system operations with glob pattern support, encoding handling, and cross-platform path utilities. Includes reading, writing, copying, directory manipulation, and advanced file matching capabilities.
Read files with various encodings and parsing options.
/**
* Read file contents as string
* @param {string} filepath - Path to file
* @param {object} [options] - Read options
* @param {string} [options.encoding='utf8'] - File encoding
* @returns {string} File contents
*/
grunt.file.read = function(filepath, options) {};
/**
* Read and parse JSON file
* @param {string} filepath - Path to JSON file
* @param {object} [options] - Read options
* @returns {*} Parsed JSON data
*/
grunt.file.readJSON = function(filepath, options) {};
/**
* Read and parse YAML file
* @param {string} filepath - Path to YAML file
* @param {object} [options] - Read options
* @param {object} [yamlOptions] - YAML parser options
* @returns {*} Parsed YAML data
*/
grunt.file.readYAML = function(filepath, options, yamlOptions) {};Usage Examples:
// Read text file
const content = grunt.file.read('src/template.html');
const binaryContent = grunt.file.read('assets/image.png', { encoding: null });
// Read JSON files
const packageJson = grunt.file.readJSON('package.json');
const config = grunt.file.readJSON('config.json');
// Read YAML files
const metadata = grunt.file.readYAML('metadata.yml');
const settings = grunt.file.readYAML('settings.yaml', {}, {
schema: 'failsafe'
});
// Error handling
try {
const data = grunt.file.readJSON('config.json');
} catch (e) {
grunt.log.error('Failed to read config: ' + e.message);
}Write files with encoding options and directory creation.
/**
* Write content to file, creating directories as needed
* @param {string} filepath - Destination file path
* @param {string} contents - Content to write
* @param {object} [options] - Write options
* @param {string} [options.encoding='utf8'] - File encoding
*/
grunt.file.write = function(filepath, contents, options) {};
/**
* Copy file or directory
* @param {string} srcpath - Source path
* @param {string} destpath - Destination path
* @param {object} [options] - Copy options
* @param {function} [options.process] - Content processing function
* @param {boolean} [options.noProcess] - Skip processing for specific files
*/
grunt.file.copy = function(srcpath, destpath, options) {};
/**
* Delete files or directories
* @param {string} filepath - Path to delete
* @param {object} [options] - Delete options
* @param {boolean} [options.force=false] - Force deletion outside CWD
*/
grunt.file.delete = function(filepath, options) {};Usage Examples:
// Write text file
grunt.file.write('dist/output.txt', 'Hello World');
grunt.file.write('dist/data.json', JSON.stringify(data, null, 2));
// Write with specific encoding
grunt.file.write('output.txt', content, { encoding: 'latin1' });
// Copy files
grunt.file.copy('src/template.html', 'dist/index.html');
// Copy with processing
grunt.file.copy('src/config.js', 'dist/config.js', {
process: function(contents, srcpath) {
return contents.replace(/\{\{VERSION\}\}/g, version);
}
});
// Copy directory
grunt.file.copy('src/assets/', 'dist/assets/');
// Delete files
grunt.file.delete('tmp/cache.json');
grunt.file.delete('dist/', { force: true });Create and manipulate directories with recursive operations.
/**
* Create directory recursively
* @param {string} dirpath - Directory path to create
* @param {number} [mode] - Directory permissions
*/
grunt.file.mkdir = function(dirpath, mode) {};
/**
* Recursively iterate over directory contents
* @param {string} rootdir - Root directory path
* @param {function} callback - Function called for each file/directory
* @param {string} [subdir] - Subdirectory path (used internally)
*/
grunt.file.recurse = function(rootdir, callback, subdir) {};
/**
* Change current working directory
* @param {...string} paths - Path components
*/
grunt.file.setBase = function(...paths) {};Usage Examples:
// Create directories
grunt.file.mkdir('dist/assets/images');
grunt.file.mkdir('build/temp', 0o755);
// Recursive directory traversal
grunt.file.recurse('src/', function(abspath, rootdir, subdir, filename) {
if (filename.endsWith('.js')) {
console.log('Found JS file:', abspath);
// Process JavaScript file
}
});
// Change working directory
grunt.file.setBase('projects', 'myproject');
// Now working in projects/myproject/Test file and directory existence and properties.
/**
* Test if path exists
* @param {...string} paths - Path components
* @returns {boolean} True if path exists
*/
grunt.file.exists = function(...paths) {};
/**
* Test if path is a symbolic link
* @param {...string} paths - Path components
* @returns {boolean} True if path is a symbolic link
*/
grunt.file.isLink = function(...paths) {};
/**
* Test if path is a directory
* @param {...string} paths - Path components
* @returns {boolean} True if path is a directory
*/
grunt.file.isDir = function(...paths) {};
/**
* Test if path is a file
* @param {...string} paths - Path components
* @returns {boolean} True if path is a file
*/
grunt.file.isFile = function(...paths) {};Usage Examples:
// Check file existence
if (grunt.file.exists('config.json')) {
const config = grunt.file.readJSON('config.json');
}
// Check multiple path components
if (grunt.file.exists('src', 'components', 'app.js')) {
// File exists at src/components/app.js
}
// Check file types
if (grunt.file.isDir('src')) {
console.log('src is a directory');
}
if (grunt.file.isFile('package.json')) {
console.log('package.json is a file');
}
// Check for symbolic links
if (grunt.file.isLink('node_modules')) {
console.log('node_modules is a symbolic link');
}Cross-platform path manipulation and testing utilities.
/**
* Test if path is absolute
* @param {...string} paths - Path components
* @returns {boolean} True if path is absolute
*/
grunt.file.isPathAbsolute = function(...paths) {};
/**
* Test if paths refer to the same location
* @param {string} first - First path
* @param {...string} others - Other paths to compare
* @returns {boolean} True if all paths are equivalent
*/
grunt.file.arePathsEquivalent = function(first, ...others) {};
/**
* Test if paths are contained within ancestor path
* @param {string} ancestor - Ancestor path
* @param {...string} descendants - Descendant paths
* @returns {boolean} True if all descendants are within ancestor
*/
grunt.file.doesPathContain = function(ancestor, ...descendants) {};
/**
* Test if path is the current working directory
* @param {...string} paths - Path components
* @returns {boolean} True if path is CWD
*/
grunt.file.isPathCwd = function(...paths) {};
/**
* Test if path is within current working directory
* @param {...string} paths - Path components
* @returns {boolean} True if path is within CWD
*/
grunt.file.isPathInCwd = function(...paths) {};Usage Examples:
// Path testing
if (grunt.file.isPathAbsolute('/usr/local/bin')) {
console.log('Absolute path');
}
// Check path equivalence
if (grunt.file.arePathsEquivalent('./src', 'src')) {
console.log('Paths are equivalent');
}
// Check path containment
if (grunt.file.doesPathContain('src', 'src/components/app.js')) {
console.log('File is within src directory');
}
// Check working directory
if (grunt.file.isPathCwd('.')) {
console.log('Current directory');
}
if (grunt.file.isPathInCwd('src/app.js')) {
console.log('File is in current working directory tree');
}Advanced file matching using glob patterns and minimatch.
/**
* Expand glob patterns to matching file paths
* @param {object} [options] - Glob options
* @param {string|string[]} patterns - Glob patterns
* @returns {string[]} Array of matching file paths
*/
grunt.file.expand = function(options, patterns) {};
/**
* Build source-destination file mappings
* @param {string|string[]} patterns - Source patterns
* @param {string} destBase - Destination base path
* @param {object} [options] - Mapping options
* @returns {object[]} Array of file mapping objects
*/
grunt.file.expandMapping = function(patterns, destBase, options) {};
/**
* Match file paths against patterns
* @param {object} [options] - Match options
* @param {string|string[]} patterns - Patterns to match against
* @param {string|string[]} filepaths - File paths to test
* @returns {string[]} Matching file paths
*/
grunt.file.match = function(options, patterns, filepaths) {};
/**
* Test if any patterns match file paths
* @param {object} [options] - Match options
* @param {string|string[]} patterns - Patterns to test
* @param {string|string[]} filepaths - File paths to test
* @returns {boolean} True if any pattern matches
*/
grunt.file.isMatch = function(options, patterns, filepaths) {};Usage Examples:
// Expand glob patterns
const jsFiles = grunt.file.expand('src/**/*.js');
const testFiles = grunt.file.expand(['test/**/*.js', '!test/fixtures/**']);
// Expand with options
const sourceFiles = grunt.file.expand({
cwd: 'src/',
filter: 'isFile'
}, ['**/*.js', '!**/*.min.js']);
// Build file mappings
const mappings = grunt.file.expandMapping(['src/*.js'], 'dist/', {
rename: function(destBase, destPath) {
return destBase + destPath.replace(/\.js$/, '.min.js');
}
});
// Match specific files
const matches = grunt.file.match(['**/*.js'], [
'app.js',
'styles.css',
'components/button.js'
]);
// Result: ['app.js', 'components/button.js']
// Test pattern matching
if (grunt.file.isMatch(['**/*.test.js'], 'components/button.test.js')) {
console.log('File matches test pattern');
}Access to underlying file system libraries used by Grunt.
/**
* The glob library for advanced file matching
* @type {object}
*/
grunt.file.glob = require('glob');
/**
* The minimatch library for pattern matching
* @type {object}
*/
grunt.file.minimatch = require('minimatch');
/**
* The findup-sync library for finding files up directory tree
* @type {function}
*/
grunt.file.findup = require('findup-sync');Usage Examples:
// Use glob directly
grunt.file.glob('src/**/*.js', function(err, files) {
if (err) {
grunt.fail.warn('Glob error: ' + err.message);
return;
}
console.log('Found files:', files);
});
// Use minimatch for pattern testing
const isMatch = grunt.file.minimatch('app.js', '*.js');
console.log('Matches pattern:', isMatch);
// Use findup to find files up directory tree
const gruntfile = grunt.file.findup('Gruntfile.js');
if (gruntfile) {
console.log('Found Gruntfile at:', gruntfile);
}Global file operation settings and defaults.
/**
* Default file encoding for read/write operations
* @type {string}
*/
grunt.file.defaultEncoding = 'utf8';
/**
* Whether to preserve BOM when reading files
* @type {boolean}
*/
grunt.file.preserveBOM = false;Usage Examples:
// Change default encoding
grunt.file.defaultEncoding = 'latin1';
// Enable BOM preservation
grunt.file.preserveBOM = true;
// These settings affect subsequent file operations
const content = grunt.file.read('file.txt'); // Uses latin1 encoding
grunt.file.write('output.txt', content); // Uses latin1 encoding