Overview
ThecreateFile function creates a new file with the specified content. Unlike writeFile, this function automatically creates parent directories if they don’t exist.
Function Signature
Parameters
The path to the file to create. Can be relative or absolute. Relative paths are resolved from the current working directory.
The content to write to the file. The content will be encoded as UTF-8.
Return Value
This function does not return a value.
Implementation Details
The function performs the following steps:- Resolves the provided file path to an absolute path using
path.resolve() - Ensures the parent directory exists by calling the internal
ensureDir()helper - Creates any missing parent directories recursively using
fs.mkdirSync()with{ recursive: true } - Writes the content to the file synchronously using
fs.writeFileSync()with UTF-8 encoding
Usage Example
Error Handling
If the file already exists, it will be overwritten. This function does not check for existing files before writing.
This is a synchronous operation and will block the event loop until the file and directories are created. For performance-critical applications, consider using asynchronous file operations.
Difference from writeFile
The key difference betweencreateFile and writeFile is:
- createFile: Automatically creates parent directories if they don’t exist
- writeFile: Requires parent directories to already exist, throws error otherwise