How to use the pathExists function from fs-extra
Find comprehensive JavaScript fs-extra.pathExists code examples handpicked from public code repositorys.
fs-extra.pathExists is a function that checks if a file or directory exists at a given path on the file system.
GitHub: clusterio/clusterio
86 87 88 89 90 91 92 93 94 95
if (extension && name.endsWith(extension)) { name = name.slice(0, -extension.length); } while (true) { if (!await fs.pathExists(path.join(directory, `${name}${extension}`))) { return `${name}${extension}`; } let match = /^(.*?)(-(\d+))?$/.exec(name);
+ 3 other calls in file
GitHub: heiseonline/embetty
31 32 33 34 35 36 37 38 39 40 41
}) const downloadAsset = async (url, baseDir) => { const { pathname } = new URL(url) const targetFile = path.join(baseDir, pathname) if (await fs.pathExists(targetFile)) { console.log('skipping download:', targetFile) return undefined }
+ 10 other calls in file
How does fs-extra.pathExists work?
fs-extra.pathExists works by taking a file path as input and returning a Promise that resolves to a Boolean value indicating whether a file or directory exists at that path.
The function first checks if the file or directory exists synchronously, without triggering any I/O operations.
If the file or directory exists, the function immediately resolves the Promise with a value of true
.
If the file or directory does not exist, the function asynchronously checks the file system to determine if the path is valid and the file or directory could be created.
If the path is valid, the function resolves the Promise with a value of false
.
If the path is invalid or the function encounters an error during the asynchronous check, the function rejects the Promise with an error message.
GitHub: maizzle/framework
112 113 114 115 116 117 118 119 120 121
tailwindConfig.content.files.push(...templateSources) } const userFilePath = get(config, 'build.tailwind.css', path.join(process.cwd(), 'src/css/tailwind.css')) const userFileExists = await fs.pathExists(userFilePath) const toProcess = [ postcssNested(), tailwindcss(tailwindConfig),
GitHub: remix-pwa/remix-pwa
329 330 331 332 333 334 335 336 337
const projectDir = process.cwd(); // Look if any lock file exists so we can identify the preferred package manager. packageManager = await (async () => { const [isNpm, isYarn, isPnpm] = await Promise.all([ fse.pathExists(path.resolve(projectDir, "package-lock.json")), fse.pathExists(path.resolve(projectDir, "yarn.lock")), fse.pathExists(path.resolve(projectDir, "pnpm-lock.yaml")), ]);
+ 14 other calls in file
Ai Example
1 2 3 4 5 6 7 8 9 10 11 12
const fs = require("fs-extra"); // Check if a file exists at the path 'file.txt' fs.pathExists("file.txt") .then((exists) => { if (exists) { console.log("The file exists."); } else { console.log("The file does not exist."); } }) .catch((err) => console.error(err));
In this example, we use the fs-extra.pathExists function to check if a file named file.txt exists at the root of the file system. We call the function with the path 'file.txt' and then handle the returned Promise using the then and catch methods. If the file exists, the Promise resolves with a value of true, and we log the message 'The file exists.'. If the file does not exist, the Promise resolves with a value of false, and we log the message 'The file does not exist.'. If an error occurs during the check, the Promise is rejected with an error message, which we log to the console using console.error.
398 399 400 401 402 403 404 405 406 407
upgradeCommand: `npm install ${pack.packageName}@${pack.latestVersion}`, uninstallCommand: `npm uninstall ${pack.packageName}` }) if (installed.includes(pack.packageName)) { const pluginPkgPath = path.join(projectDir, 'node_modules', pack.packageName, 'package.json') const pluginPkg = await fse.pathExists(pluginPkgPath) ? await fse.readJson(pluginPkgPath) : {} pack.installedVersion = pluginPkg.version if (!['govuk-prototype-kit', 'govuk-frontend'].includes(pack.packageName)) { pack.uninstallLink = `${contextPath}/plugins/uninstall?package=${encodeURIComponent(pack.packageName)}` }
+ 2 other calls in file
GitHub: data-fair/data-fair
68 69 70 71 72 73 74 75 76 77 78
return path.join(exports.dir(dataset), 'metadata-attachments') } exports.lsAttachments = async (dataset) => { const dirName = exports.attachmentsDir(dataset) if (!await fs.pathExists(dirName)) return [] const files = (await dir.promiseFiles(dirName)) .map(f => path.relative(dirName, f)) return files.filter(p => path.basename(p).toLowerCase() !== 'thumbs.db') }
+ 23 other calls in file
GitHub: data-fair/data-fair
492 493 494 495 496 497 498 499 500 501
if (patch.exports.restToCSV.active) { const job = new CronJob(config.exportRestDatasets.cron, () => {}) patch.exports.restToCSV.nextExport = job.nextDates().toISOString() } else { delete patch.exports.restToCSV.nextExport if (await fs.pathExists(datasetUtils.exportedFilePath(req.dataset, '.csv'))) { await fs.remove(datasetUtils.exportedFilePath(req.dataset, '.csv')) } } patch.exports.restToCSV.lastExport = req.dataset?.exports?.restToCSV?.lastExport
+ 19 other calls in file
165 166 167 168 169 170 171 172 173 174
// Add base64 content of attachments const attachmentField = dataset.schema.find(f => f['x-refersTo'] === 'http://schema.org/DigitalDocument') if (attachmentField && flatItem[attachmentField.key]) { const filePath = path.join(datasetUtils.attachmentsDir(dataset), flatItem[attachmentField.key]) if (await fs.pathExists(filePath)) { const stats = await fs.stat(filePath) if (stats.size > config.defaultLimits.attachmentIndexed) { warning = 'Pièce jointe trop volumineuse pour être analysée' } else {
+ 13 other calls in file
GitHub: athombv/node-homey
560 561 562 563 564 565 566 567 568 569
// Driver Icon Hashes if (Array.isArray(manifest.drivers)) { await Promise.all(manifest.drivers.map(async driver => { const iconPath = path.join(this.path, 'drivers', driver.id, 'assets', 'icon.svg'); if (await fse.pathExists(iconPath)) { driver.iconHash = await Util.getFileHash(iconPath); } })); }
+ 7 other calls in file
36 37 38 39 40 41 42 43 44 45
readFileAsync = (fname, encoding) => fse.readFile(getAbsPath(fname),encoding) readJsonAsync = fname => fse.readJSON(getAbsPath(fname)) readdirAsync = dirname => fse.readdir(getAbsPath(dirname)) statAsync = path => fse.stat(getAbsPath(path)) readJson = fname => fse.readJSON(getAbsPath(fname)) pathExistsAsync = fname => fse.pathExists(getAbsPath(fname)) copyAsync = (src, dest) => fse.copy(src,dest) ensureDirAsync = dirPath => fse.ensureDir(dirPath) moveAsync = (srcPath,destPath) => fse.move(srcPath,destPath) removeAsync = dirPath => fse.remove(dirPath)
636 637 638 639 640 641 642 643 644 645
return gitBranch } const { gitRepositoryUrl, workspacePath } = config let localRemoteExists if ( await fs.pathExists( `${workspacePath}/.git/refs/remotes/origin/${gitBranch}` ) ) { localRemoteExists = true
+ 11 other calls in file
322 323 324 325 326 327 328 329 330 331
//will remove "appId".json from .nodered/allFlows directory let removeJSON = (flowDetails) => { console.log("removeJSON : packageId : " + flowDetails.packageId); return new Promise((resolve, reject) => { let allPath = userDir + '/allFlows/' + flowDetails.packageId + ".json"; fs.pathExists(allPath).then(exists => { if (exists) { fs.unlink(allPath, (err) => { if (err) { reject("Error : App not exists in allFlows folder :" + flowDetails.packageId);
711 712 713 714 715 716 717 718 719
*/ static async _scanFileSystem(scanDir){ let res = new Set() if(await fs.pathExists(scanDir)) { const files = await fs.readdir(scanDir) for(let i=0; i<files.length; i++){
+ 7 other calls in file
GitHub: verdnatura/myt
156 157 158 159 160 161 162 163 164 165
console.log('Mocking date functions.'); const mockDateScript = path.join(dumpDir, 'mockDate.sql'); if (opts.mockDate) { if (!await fs.pathExists(mockDateScript)) throw new Error(`Date mock enabled but mock script does not exist: ${mockDateScript}`); let sql = await fs.readFile(mockDateScript, 'utf8'); sql = sql.replace(/@mockDate/g, SqlString.escape(opts.mockDate));
+ 3 other calls in file
777 778 779 780 781 782 783 784 785 786
// see if a package.json exists; if so read it // in, because there may be a "main" field // that indicates the name of the file which // includes the main routine const packageJsonPath = `${dirPath}/package.json` fs.pathExists(packageJsonPath) .then(exists => { if (exists) { // yup, we found a package.json, now see if it has a main field return fs.readFile(packageJsonPath)
4 5 6 7 8 9 10 11 12 13 14 15
const yaml = require("./yaml") const deepmerge = require("./deepmerge") const getConfigYaml = async (file) => { if (!(await fs.pathExists(file))) { return } return yaml.load(await fs.readFile(file, { encoding: "utf-8" })) }
+ 9 other calls in file
GitHub: cavnav/f-photo2
669 670 671 672 673 674 675 676 677 678
doNeedTopLevelSearch = true, doNeedDirs = false, doNeedFullPath = false, }) { const statSync = fs.statSync; const isReqPathExists = await fs.pathExists(reqPath); let browseFiles = []; if (isReqPathExists) { const files = await new Promise((resolve) => find.file(reqPath, resolve)); browseFiles = files;
+ 39 other calls in file
GitHub: verdnatura/myt
64 65 66 67 68 69 70 71 72
if (!/^[a-z]+$/.test(commandName)) throw new Error (`Invalid command name '${commandName}'`); const commandFile = path.join(__dirname, `myt-${commandName}.js`); if (!await fs.pathExists(commandFile)) throw new Error (`Unknown command '${commandName}'`); Command = require(commandFile); }
+ 19 other calls in file
123 124 125 126 127 128 129 130 131 132
// Find all files we want to scan while (packageDirQueue.length) { const packageDir = packageDirQueue.pop(); const srcDir = resolvePath(rootPath, packageDir, 'src'); if (await fs.pathExists(srcDir)) { const files = await globby(['**/*.{js,jsx,ts,tsx,mjs,cjs}'], { cwd: srcDir, }); fileQueue.push(
354 355 356 357 358 359 360 361 362 363
}), ); const excludeList = []; const prePath = path.resolve(changesetPath, 'pre.json'); if (await fs.pathExists(prePath)) { const data = await fs.readJSON(prePath); // Only exclude changesets in pre-release mode. if (data.mode === 'pre') { excludeList.push(...data.changesets.map(name => `${name}.md`));
fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)