How to use the pathExistsSync function from fs-extra

Find comprehensive JavaScript fs-extra.pathExistsSync code examples handpicked from public code repositorys.

fs-extra.pathExistsSync is a synchronous function that checks if a file or directory exists at a given path.

489
490
491
492
493
494
495
496
497
498
499
    }
});


gulp.task('verifyUnhandledErrors', async () => {
    const fileName = path.join(__dirname, 'unhandledErrors.txt');
    const contents = fs.pathExistsSync(fileName) ? fs.readFileSync(fileName, 'utf8') : '';
    if (contents.trim().length) {
        console.error(contents);
        throw new Error('Unhandled errors detected. Please fix them before merging this PR.', contents);
    }
fork icon209
star icon955
watch icon43

+ 9 other calls in file

500
501
502
503
504
505
506
507
508
509
if (params.cmd === 'newfile' ) {
    fullname = path.join(fullname, params.fname)
}

// Does folder or file already exist? If so, return error
if ( fs.pathExistsSync(fullname) ) {
    const statusMsg = `selected ${params.cmd === 'newfolder' ? 'folder' : 'file'} already exists. url=${params.url}, cmd=${params.cmd}, folder=${params.folder}`
    log.error(`[uibuilder:adminRouterV3:POST] Admin API. ${statusMsg}`)
    res.statusMessage = statusMsg
    res.status(500).end()
fork icon75
star icon346
watch icon24

+ 12 other calls in file

How does fs-extra.pathExistsSync work?

fs-extra.pathExistsSync is a synchronous function provided by the fs-extra module in Node.js that checks if a given file or directory path exists in the file system.

It takes a single argument, which is the path to the file or directory to be checked. The function returns a boolean value of true if the path exists and false otherwise.

Unlike the asynchronous fs-extra.pathExists() function, pathExistsSync() does not use a callback function or return a Promise, making it simpler to use in situations where a synchronous approach is desired.

71
72
73
74
75
76
77
78
79
80
  integrateManifest(projectDir, lang, dir);
}

// Register worker in `entry.client.tsx`
const remoteClientPath = projectDir + `/${dir}/entry.client.` + lang + "x";
const remoteClientExists = fse.pathExistsSync(remoteClientPath);
const remoteClientContent: string = remoteClientExists ? fse.readFileSync(remoteClientPath).toString() : "";
const ClientContent = fse.readFileSync(appDir + "/entry.client." + lang).toString();

// If client entry file is not available reveal it with `remix reveal entry.client`
fork icon16
star icon293
watch icon5

+ 4 other calls in file

206
207
208
209
210
211
212
213
214
215
)
.description(`build your app for production`)
.action(async ({buildDirectory}) => {
    const webpack = p.join(require.resolve('webpack'), '..', '..', '..', '.bin', 'webpack')
    const projectWebpack = p.join(process.cwd(), 'webpack.config.js')
    const webpackConf = fse.pathExistsSync(projectWebpack)
        ? projectWebpack
        : p.join(__dirname, '..', 'configs', 'webpack', 'config.js')
    fse.emptyDirSync(buildDirectory)
    execSync(`${webpack} --config ${webpackConf}`, {
fork icon73
star icon177
watch icon16

+ 9 other calls in file

Ai Example

1
2
3
4
5
6
7
const fs = require("fs-extra");

if (fs.pathExistsSync("/path/to/my/file.txt")) {
  console.log("The file exists!");
} else {
  console.log("The file does not exist.");
}

In this example, fs-extra.pathExistsSync() is used to check if the file at /path/to/my/file.txt exists. If it does, the message "The file exists!" is logged to the console; otherwise, the message "The file does not exist." is logged.

1
2
3
4
5
6
7
8
9
10
11
const fs = require('fs-extra')
// const { copyFile } = fs.promises
// ['access', 'copyFile', 'open', 'opendir', 'rename', 'truncate', 'rmdir', 'mkdir', 'readdir', 'readlink', 'symlink', 'lstat', 'stat', 'link', 'unlink', 'chmod', 'lchmod', 'lchown', 'chown', 'utimes', 'realpath', 'mkdtemp', 'writeFile', 'appendFile', 'readFile']


function getFiles(source, dest) {
  if (fs.pathExistsSync(source) && fs.pathExistsSync(dest)) {
    const sourceList = fs.readdirSync(source, { encoding: 'utf-8' })
    const destList = fs.readdirSync(dest, { encoding: 'utf-8' })
    return { sourceList, destList }
  }
fork icon0
star icon3
watch icon0

18
19
20
21
22
23
24
25
26
27
28
29
	// 增加编译速度
	...module.paths
];


const resolvePackage = (source) => {
	let $path = NMS.find(i => fs.pathExistsSync(resolve(i, source)));


	if (!$path) {
		throw new Error(`@wya/doc: 未找到${source}`);
	}
fork icon2
star icon1
watch icon3

+ 15 other calls in file

17
18
19
20
21
22
23
24
25
26
27
 * @description: find config.yaml location
 * @return {string}
 */
const getConfigPath = () => {
    const configPathList = [path.join(process.cwd(), 'config.yml'), path.join(process.cwd(), '../config.yml')]
    return configPathList.find(_path => fse.pathExistsSync(_path))
}


/**
 * @description create yml option file
fork icon0
star icon1
watch icon1

+ 13 other calls in file

188
189
190
191
192
193
194
195
196
197
})

describe('removeFile', () => {
  it(`Should remove a file if it exists`, async () => {
    await writeYmlFile(testYmlPath, testYmlData)
    const exists = await pathExistsSync(testYmlPath)
    expect(exists).toBe(true)

    await removeFile(testYmlPath)
    const stillExists = await pathExistsSync(testYmlPath)
fork icon1
star icon0
watch icon1

+ 35 other calls in file

163
164
165
166
167
168
169
170
171
172
exports.Cache = Cache;
//======[CACHES MANAGER]================================================================================================
class CacheManager {
    rootLocation;
    cacheExists(name) {
        return fs.pathExistsSync(path.join(this.rootLocation, name));
    }
    initiateNewCache(name, overwrite = false) {
        name = (name || "").replace(/([^A-Za-z0-9_-]+)/gi, "");
        const loc = path.join(this.rootLocation, name);
fork icon0
star icon0
watch icon1

76
77
78
79
80
81
82
83
84
85
let currentPath = targetPath;

// Some confidence check to avoid infinite loop
for (let i = 0; i < 100; i++) {
  const packagePath = path.resolve(currentPath, 'package.json');
  const exists = fs.pathExistsSync(packagePath);
  if (exists) {
    try {
      const data = fs.readJsonSync(packagePath);
      if (!closestPkgJson) {
fork icon0
star icon0
watch icon1

10
11
12
13
14
15
16
17
 * @returns {boolean}
 */
module.exports = (dir, filename = undefined) => {
  const filePath = getConfigPath(dir, { filename });


  return fse.pathExistsSync(filePath);
};
fork icon0
star icon0
watch icon1

+ 6 other calls in file

31
32
33
34
35
36
37
38
39
40
41
42


/**
 * Check if given path existing
 * @param {string} filepath
 */
const fileExist = filepath => fs.pathExistsSync(filepath);


/**
 * Read file content
 * @param {string} filepath
fork icon0
star icon0
watch icon1

+ 4 other calls in file

1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
});
module.rspackOutputPath = '/my/Service/Path/outputPath';
fsExtraMock.pathExists.mockImplementation((p, cb) =>
  cb(null, false),
);
fsExtraMock.pathExistsSync.mockReturnValue(true);
fsExtraMock.copy.mockImplementation((from, to, cb) => cb());
packagerFactoryMock
  .get('npm')
  .getProdDependencies.mockReturnValue(
fork icon0
star icon0
watch icon0

+ 4 other calls in file

226
227
228
229
230
231
232
233
234
235
  });
});

describe('with lock file', () => {
  it('should use npm ls when lock file is not version 2', () => {
    fseMock.pathExistsSync.mockReturnValue(true);
    fsMock.readFileSync.mockReturnValue(
      JSON.stringify({ lockfileVersion: 1 }),
    );
    Utils.spawnProcess.mockReturnValue(
fork icon0
star icon0
watch icon0

+ 8 other calls in file

3
4
5
6
7
8
9
10
11
12
const path = tslib_1.__importStar(require("path"));
const fs = tslib_1.__importStar(require("fs-extra"));
const cli_ux_1 = tslib_1.__importDefault(require("cli-ux"));
function checkTos(options) {
    const tosPath = path.join(options.config.cacheDir, 'terms-of-service');
    const viewedBanner = fs.pathExistsSync(tosPath);
    const message = 'Our terms of service have changed: https://dashboard.heroku.com/terms-of-service';
    if (!viewedBanner) {
        cli_ux_1.default.warn(message);
        fs.createFile(tosPath);
fork icon0
star icon0
watch icon0

function icon

fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)