How to use the existsSync function from fs-extra

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

fs-extra.existsSync is a method that checks if a given file or directory exists in the file system.

13
14
15
16
17
18
19
20
21
22
23
24
const { appDir } = require('./utils/paths')


const appConfigPath = path.join(appDir, 'config.json')


function getConfigFromFile () {
  const configFileExists = fse.existsSync(appConfigPath)
  if (configFileExists) {
    try {
      return fse.readJsonSync(appConfigPath)
    } catch (e) {
fork icon234
star icon281
watch icon77

+ 2 other calls in file

249
250
251
252
253
254
255
256
257
258
259
};


const setupTempWorkingDir = () => {
  let workdir;
  const tmpBaseDir = os.tmpdir();
  while (!workdir || fs.existsSync(workdir)) {
    workdir = path.join(tmpBaseDir, crypto.randomBytes(20).toString('hex'));
  }
  fs.mkdirSync(workdir);
  return workdir;
fork icon168
star icon237
watch icon0

How does fs-extra.existsSync work?

fs-extra.existsSync is a method in the fs-extra module that checks whether a file or directory exists on the file system, returning a boolean value indicating its presence or absence. It is a synchronous version of the fs.exists function, with the added functionality of checking for existence of both files and directories. It takes a single parameter, the path to the file or directory that needs to be checked, and returns true if it exists, false otherwise.

312
313
314
315
316
317
318
319
320
321

// Load extension manifest and default icon
yield crx.load(crxPath);

// Do we have a local icon to copy over?
if (crxConfig.icon && fs.existsSync(crxConfig.icon)) {
    // Set target copy path as current extension icon's path
    var copyToPath = crx.path + '/' + crx.manifest.icons['128'];

    // Copy the local file to the current extension's folder, where the icon currently resides
fork icon86
star icon477
watch icon0

573
574
575
576
577
578
579
580
581
582

describe("# test helper method - attemptUpgradeUndeployedProject", () => {
  beforeEach(() => {
    sinon.stub(fs, "existsSync");
    fs.existsSync.withArgs(path.join(TEST_ROOT_PATH, CONSTANTS.FILE_PATH.SKILL_PACKAGE.MANIFEST)).returns(true);
    fs.existsSync.withArgs(path.join(TEST_ROOT_PATH, "models")).returns(true);
    fs.existsSync.withArgs(path.join(TEST_ROOT_PATH, "isps")).returns(true);
    fs.existsSync.callThrough();
    sinon.stub(fs, "readJSONSync").returns(formSkillJson("manifest", {endpoint: TEST_ARN}));
    sinon.stub(fs, "removeSync");
fork icon50
star icon139
watch icon40

+ 9 other calls in file

Ai Example

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

if (fs.existsSync("/path/to/file")) {
  console.log("File exists!");
} else {
  console.log("File does not exist.");
}

In this example, the code checks whether a file exists at the given path by calling fs.existsSync() with the file path as an argument. If the file exists, the code logs a message indicating so. If the file does not exist, the code logs a different message.

1195
1196
1197
1198
1199
1200
1201
1202
1203
1204

// If translated assets exist, use that path,
// otherwise use the parent assets.
let pathToAssets
if (argv.language &&
          fs.existsSync(pathToTranslatedAssets) &&
          fs.readdirSync(pathToTranslatedAssets).length > 0) {
  pathToAssets = pathToTranslatedAssets
} else {
  pathToAssets = pathToParentAssets
fork icon39
star icon105
watch icon0

346
347
348
349
350
351
352
353
354
355
 * Copies over README.md or Home.md to default index.md if present.
 */
async addIndexPage() {
  const indexPagePath = path.join(this.rootPath, INDEX_MARKDOWN_FILE);
  const fileNames = ['README.md', 'Home.md'];
  const filePath = fileNames.find(fileName => fs.existsSync(path.join(this.rootPath, fileName)));
  // if none of the files exist, do nothing
  if (_.isUndefined(filePath)) return;
  try {
    await fs.copy(path.join(this.rootPath, filePath), indexPagePath);
fork icon105
star icon94
watch icon13

+ 6 other calls in file

2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840


    return [{}];
}


DataPacksUtils.prototype.handleDataPackEventSync = function(eventName, dataPackType, input) {
    if (!this[dataPackType] && fs.existsSync(path.join(__dirname, 'datapacktypes', dataPackType.toLowerCase() + '.js'))) {
        let requiredDataPack = require(path.join(__dirname, 'datapacktypes', dataPackType.toLowerCase() + '.js'));
        this[dataPackType] = new requiredDataPack(this.vlocity);
    }

fork icon82
star icon94
watch icon26

+ 19 other calls in file

592
593
594
595
596
597
598
599
600
601
const packageFolders = fs
  .readdirSync(packageFolder, { withFileTypes: true })
  .filter(fileName => {
    return (
      fileName.isDirectory() &&
      fs.existsSync(path.join(packageFolder, fileName.name, 'package.json'))
    );
  });
if (packageFolders.length === 0) {
  console.error(`"${packageFolder}" does not contain a package or packages. Not upgrading.`);
fork icon58
star icon932
watch icon20

+ 3 other calls in file

310
311
312
313
314
315
316
317
318
case 'checkurls': {
    log.trace(`[uibuilder:adminRouterV3:GET:checkurls] Check if URL is already in use. URL: ${params.url}`)

    /** @returns {boolean} True if the given url exists, else false */
    const chkInstances = Object.values(uib.instances).includes(params.url)
    const chkFolders = fs.existsSync(path.join(uib.rootFolder, params.url))

    res.statusMessage = 'Instances and Folders checked'
    res.status(200).json( chkInstances || chkFolders )
fork icon75
star icon346
watch icon24

+ 38 other calls in file

491
492
493
494
495
496
497
498
499
500
const filePathRoot = path.join(uib.rootFolder, params.url, params.folder)
// @ts-ignore
const filePath = path.join(filePathRoot, req.query.fname)

// Does the file exist?
if ( fs.existsSync(filePath) ) {
    // Send back a plain text response body containing content of the file
    res.type('text/plain').sendFile(
        // @ts-ignore
        req.query.fname,
fork icon75
star icon346
watch icon24

+ 25 other calls in file

577
578
579
580
581
582
583
584
585
586

if (uib.configFolder === null) throw new Error('uib.configFolder is undefined')

// Try to load the sioUse middleware function - sioUse applies to all incoming msgs
const mwfile = path.join(uib.configFolder, uib.sioUseMwName)
if ( fs.existsSync(mwfile) ) { // not interested if the file doesn't exist
    try {
        const sioUseMw = require( mwfile )
        if ( typeof sioUseMw === 'function' ) { // if exported, has to be a function
            socket.use(sioUseMw)
fork icon75
star icon346
watch icon24

+ 11 other calls in file

626
627
628
629
630
631
632
633
634
635

// Our fake jQuery copy contains only package.json but the true one has the /dist/
// sub-directory. We'll use it to check if the `install` command was invoked
// when technically not needed as we require it now always when pruning.
assert.strictEqual(
    fs.existsSync(`${fixtureCopyDir}/${depsDirName}/jquery/dist`),
    false,
);

Promise.all([])
fork icon30
star icon115
watch icon0

+ 19 other calls in file

42
43
44
45
46
47
48
49
50
51
  fse.mkdirSync(projectDir + `/${dir}/routes/resources`, { recursive: true });
}

const subscribeContent = fse.readFileSync(appDir + `/routes/resources/subscribe.${lang}`).toString();

fse.existsSync(projectDir + `/${dir}/routes/resources/subscribe.` + lang)
  ? null
  : fse.writeFileSync(projectDir + `/${dir}/routes/resources/subscribe.${lang}`, subscribeContent);

// `/utils/server/pwa-utils.server.ts`
fork icon16
star icon293
watch icon5

+ 19 other calls in file

392
393
394
395
396
397
398
399
400
401

// inject env hook
let inject_env = !isPackaged ? `"${path.join(__dirname, '..', "\\env\\python\\condabin\\conda_hook.bat")}" && "${path.join(__dirname, '..', "\\env\\python\\condabin\\conda_auto_activate.bat")}"` : `"${path.join(process.resourcesPath, "\\env\\python\\condabin\\conda_hook.bat")}" && "${path.join(process.resourcesPath, "\\env\\python\\condabin\\conda_auto_activate.bat")}"`;

let tmpOutPath = path.join(cache, Date.now() + ".mkv");
if (extension != ".mkv" && fse.existsSync(subsPath) == true) {
    openModal(subsModal);
    terminal.innerHTML += "\r\n[enhancr] Input video contains subtitles, but output container is not .mkv, cancelling.";
    sessionStorage.setItem('status', 'error');
    throw new Error('Input video contains subtitles, but output container is not .mkv');
fork icon15
star icon182
watch icon7

+ 9 other calls in file

63
64
65
66
67
68
69
70
71
72
73
var staticMiddlewareManifestUI = express.static(path.join(__dirname, 'www4'));
var staticMiddlewareWizard = express.static(path.join(__dirname, 'wizard'));


app.use(function (req, res, next) {
  var userAgent = req.get('user-agent');
  if (process.env.NEW_WIZARD === 'true' && fs.existsSync(volumioWizardFlagFile)){
    staticMiddlewareWizard(req, res, next);
  } else {
    if (fs.existsSync(volumioManifestUIDir) && !fs.existsSync(volumioManifestUIDisabledFile)){
      staticMiddlewareManifestUI(req, res, next);
fork icon28
star icon21
watch icon4

+ 6 other calls in file

148
149
150
151
152
153
154
155
156
157
        extensionsArr.push(id);
    }
}

async function isAvailable(extVsixPath, extensionName, extensionVersion, namespace = 'vscode') {
    if (extVsixPath && fs.existsSync(extVsixPath)) {
        return Promise.resolve(true);
    }

    return isPublished(extensionVersion, extensionName, namespace);
fork icon32
star icon58
watch icon15

1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
        test = po.test ?? po.value ?? undefined;
        value = po.value ?? test ?? undefined;
    } else {
        test = value = po;
    }
    if (test && value && fs.existsSync(test)) {
        n = value;
        break;
    }
}
fork icon6
star icon20
watch icon3

+ 4 other calls in file

0
1
2
3
4
5
6
7
8
9
10
const fs = require('fs-extra');
const beginningUpdated = `${fs.statSync(`./index.js`).mtimeMs}`;
const { fork, execSync } = require('child_process');
const tmout = (ms) => new Promise(r => setTimeout(r, ms));
const moment = require('moment');
const logDebugs = process.argv.find(s => s.includes(`debug`)) || fs.existsSync(`./config.json`) ? require(`./config.json`).debug || false : false;
//const logDebugs = true; // always log debugs; no point in not doing it


let io = null;

fork icon1
star icon4
watch icon1

+ 5 other calls in file

168
169
170
171
172
173
174
175
176
  // get the list of potential parents
  const ppsjons = require('../utils/traverse-up')(['package.json'], path.resolve(this.root, '..'));
  // remove the root
  ppsjons.pop();
  // paternity test
  const pjsons = ppsjons.filter(pjson => fs.existsSync(pjson));
  // if we have parents then use the closest
  if (pjsons.length > 0) this.version = require(pjsons[0]).version;
}
fork icon0
star icon1
watch icon0

+ 4 other calls in file

833
834
835
836
837
838
839
840
841
842
 * @param {*} options
 * @returns
 */
//========================================================================================================================================
Void.sendImage = async(jid, path, caption = '', quoted = '', options) => {
    let buffer = Buffer.isBuffer(path) ? path : /^data:.*?\/.*?;base64,/i.test(path) ? Buffer.from(path.split `,` [1], 'base64') : /^https?:\/\//.test(path) ? await (await getBuffer(path)) : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0)
    return await Void.sendMessage(jid, { image: buffer, caption: caption, ...options }, { quoted })
}

/**
fork icon0
star icon1
watch icon1

function icon

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