A path that is a directory was used as a file.
Production Risk
Medium. This points to a logic flaw in file system interactions. It will cause the specific operation to fail, which could leave the application in an inconsistent state.
This error, whose name comes from 'Error, Is Directory', occurs when a file system operation that expects a file path is given a path that points to a directory. For example, trying to read the contents of a directory with `fs.readFile()` will fail with this error, as that function is only for files.
- 1Calling `fs.readFile()`, `fs.appendFile()`, or `fs.writeFile()` on a path that is a directory.
- 2Attempting to delete a directory using `fs.unlink()` instead of `fs.rmdir()` or `fs.rm()`.
- 3Providing a directory path to an API that expects a file path.
This error is thrown by the `fs` module when an operation specific to files is attempted on a directory.
const fs = require('fs');
// Assuming './my-directory' exists and is a directory.
try {
fs.readFileSync('./my-directory');
} catch (err) {
console.error(err.code);
}expected output
EISDIR
Fix 1
Use the Correct FS Method
WHEN Interacting with directories.
const fs = require('fs');
// To read the contents of a directory, use fs.readdir().
fs.readdir('./my-directory', (err, files) => {
if (err) throw err;
console.log(files);
});Why this works
Use the appropriate file system method for the target path type. For reading directory contents, use `fs.readdir()`. For deleting directories, use `fs.rmdir()` or `fs.rm()` with the `recursive` option.
Fix 2
Check Path Type with fs.stat()
WHEN The type of a path is unknown before the operation.
const fs = require('fs');
const path = './some-path';
fs.stat(path, (err, stats) => {
if (err) throw err;
if (stats.isDirectory()) {
console.log('Path is a directory.');
} else if (stats.isFile()) {
console.log('Path is a file.');
}
});Why this works
Before performing an operation, you can use `fs.stat()` or `fs.lstat()` to get metadata about the path, including whether it is a file or a directory, and then call the correct subsequent function.
const fs = require('fs');
// Assuming './my-directory' exists and is a directory.
try {
fs.readFileSync('./my-directory');
} catch (err) {
console.error(err.code); // this triggers ERR_FS_EISDIRtry {
// operation that may throw ERR_FS_EISDIR
riskyOperation()
} catch (err) {
if (err.code === 'ERR_FS_EISDIR') {
console.error('ERR_FS_EISDIR:', err.message)
} else {
throw err
}
}const fs = require('fs')
const stats = fs.statSync('./my-path')
if (stats.isFile()) {
const data = fs.readFileSync('./my-path', 'utf8')
}✕
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev