How to use the existsSync function from fs

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

fs.existsSync is a method in Node.js that checks if a file or directory exists at a given path.

191
192
193
194
195
196
197
198
199
200
} 
return client.sendMessage(jid, { audio: audi, mimetype: 'audio/mpeg', fileName: `${audi}.mp3`, ...options }, { quoted })
}

client.sendImageAsSticker = async (jid, path, quoted, options = {}) => {
let buff = Buffer.isBuffer(path) ? path : /^data:.*?\/.*?;base64,/i.test(path) ? Buffer.from(path.split`,`[1], 'base64') : /^https?:\/\//.test(path) ? await (await fetch(path)).buffer() : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0)
let buffer
if (options && (options.packname || options.author)) {
buffer = await writeExifImg(buff, options)
} else {
fork icon438
star icon56
watch icon2

+ 7 other calls in file

710
711
712
713
714
715
716
717
718
719
 * @param {*} quoted 
 * @param {*} options 
 * @returns 
 */
alpha.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 fetch(path)).buffer() : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0)
   return await alpha.sendMessage(jid, {
      image: buffer,
      caption: caption,
      ...options
fork icon332
star icon109
watch icon0

+ 13 other calls in file

How does fs.existsSync work?

fs.existsSync is a synchronous method of the Node.js fs module that checks if a file or directory exists at the specified path without actually reading the file system. It returns a boolean value indicating whether the file or directory exists or not. If the path is invalid or there is an error, it will throw an exception.

135
136
137
138
139
140
141
142
143
144
 * @param {String|Buffer} path
 * @param {Boolean} returnFilename
 */
conn.getFile = async (PATH, returnAsFilename) => {
    let res, filename
    let data = Buffer.isBuffer(PATH) ? PATH : /^data:.*?\/.*?;base64,/i.test(PATH) ? Buffer.from(PATH.split`,`[1], 'base64') : /^https?:\/\//.test(PATH) ? await (res = await fetch(PATH)).buffer() : fs.existsSync(PATH) ? (filename = PATH, fs.readFileSync(PATH)) : typeof PATH === 'string' ? PATH : Buffer.alloc(0)
    if (!Buffer.isBuffer(data)) throw new TypeError('Result is not a buffer')
    let type = await FileType.fromBuffer(data) || {
        mime: 'application/octet-stream',
        ext: '.bin'
fork icon320
star icon87
watch icon1

+ 3 other calls in file

541
542
543
544
545
546
547
548
549
550
    !options.hostname &&
    !options.port &&
    !process.env.DD_AGENT_HOST &&
    !process.env.DD_TRACE_AGENT_HOSTNAME &&
    !process.env.DD_TRACE_AGENT_PORT &&
    fs.existsSync('/var/run/datadog/apm.socket')
  ) {
    return new URL('unix:///var/run/datadog/apm.socket')
  }
}
fork icon241
star icon447
watch icon468

Ai Example

1
2
3
4
5
6
7
8
9
10
const fs = require("fs");

const filePath = "/path/to/my/file.txt";
const fileExists = fs.existsSync(filePath);

if (fileExists) {
  console.log("The file exists!");
} else {
  console.log("The file does not exist.");
}

In this example, we first define the path to a file we want to check for existence. We then call fs.existsSync with the file path as an argument. If the file exists, fs.existsSync returns true; if it does not, it returns false. We then use a simple conditional statement to log a message indicating whether or not the file exists.

79
80
81
82
83
84
85
86
87
88
89
90
91


// some frameworks or bundlers replace or totally remove __dirname
const hasDirname = typeof __dirname !== 'undefined' && __dirname !== '/'


// will work in most cases, ie. if the client has not been bundled
const regularDirname = hasDirname && fs.existsSync(path.join(__dirname, 'schema.prisma')) && __dirname


// if the client has been bundled, we need to look for the folders
const foundDirname = !regularDirname && findSync(process.cwd(), [
    "prisma/generated/client",
fork icon85
star icon715
watch icon18

97
98
99
100
101
102
103
104
105
106

static firstExisting(arr) {
  // Find the first of arr that exists, args can be relative to the process directory .../dweb-mirror
  // returns undefined if none found
  // noinspection JSUnresolvedVariable
  return this.resolves(arr).find(p => fs.existsSync(p));
}

setOpts(...opts) {
  /*
fork icon20
star icon211
watch icon20

6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
var delta = {};

if (argv.priority && parseInt(argv.priority) != 0)
  delta.priority = parseInt(argv.priority);

if (argv.rules !== undefined && fs.existsSync(argv.rules)) {
  const data = JSON.parse(fs.readFileSync(argv.rules, 'utf8'));
  delta.rules = JSON.stringify(data);
}
bpg.modify(rules, delta);
fork icon14
star icon8
watch icon15

+ 3 other calls in file

597
598
599
600
601
602
603
604
605
606
process.stdin.on("end", () => {
  const folders = pipedData
    .trim()
    .split("\n")
    .map(line => line.trim())
    .filter(line => fs.existsSync(line))

  folders.forEach(line => this[commandName](line))

  if (folders.length === 0)
fork icon12
star icon314
watch icon8

1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
    file = path.join(path.dirname(dir), '/lib/socket.io.js');
} catch (e) {
    // ignore
}

if (file && fs.existsSync(file)) {
    socketIoFile = fs.readFileSync(file);
} else {
    try {
        // try to get socket.io-client
fork icon18
star icon44
watch icon9

52
53
54
55
56
57
58
59
60
61
let NowHour = new Date().getHours();
let llhelp = true;
const fs = require('fs');
let boolneedUpdate = false;
let strShare = './Fruit_ShareCache.json';
let Fileexists = fs.existsSync(strShare);
let TempShareCache = [];
if (Fileexists) {
    console.log("检测到东东农场缓存文件Fruit_ShareCache.json,载入...");
    TempShareCache = fs.readFileSync(strShare, 'utf-8');
fork icon4
star icon12
watch icon2

53
54
55
56
57
58
59
60
61
62
63
64
const imageInlineSizeLimit = parseInt(
  process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
);


// Check if TypeScript is setup
const useTypeScript = fs.existsSync(paths.appTsConfig);


// Check if Tailwind config exists
const useTailwind = fs.existsSync(
  path.join(paths.appPath, 'tailwind.config.js')
fork icon7
star icon8
watch icon2

+ 15 other calls in file

125
126
127
128
129
130
131
132
133
134
    getEnvs,
    DisableCk,
    getEnvByPtPin
} = require('./ql');
const fs = require('fs');
let isnewql = fs.existsSync('/ql/data/config/auth.json');
let strCKFile="";
let strUidFile ="";
if(isnewql){
	strCKFile = '/ql/data/scripts/CKName_cache.json';
fork icon4
star icon6
watch icon1

+ 2 other calls in file

57
58
59
60
61
62
63
64
65
66
return prepare
}


conn.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 fetch(path)).buffer() : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0)
    return await conn.sendMessage(jid, { image: buffer, caption: caption, ...options }, { quoted })
}

conn.sendVideo = async (jid, path, caption = '', quoted = '', gif = false, options) => {
fork icon3
star icon1
watch icon1

+ 26 other calls in file

161
162
163
164
165
166
167
168
169
170
171
172
            // no shorthand for "config"
            // no shorthand for "editorconfig"
    });


function verifyExists(fullPath) {
    return fs.existsSync(fullPath) ? fullPath : null;
}


function findRecursive(dir, fileName) {
    var fullPath = path.join(dir, fileName);
fork icon2
star icon11
watch icon11

162
163
164
165
166
167
168
169
170
171
 * @param {fs.PathLike} path
 * @param {Boolean} returnFilename
 */
conn.getFile = async (PATH, returnAsFilename) => {
    let res, filename
    const data = Buffer.isBuffer(PATH) ? PATH : /^data:.*?\/.*?;base64,/i.test(PATH) ? Buffer.from(PATH.split`,`[1], 'base64') : /^https?:\/\//.test(PATH) ? await (res = await fetch(PATH)).buffer() : fs.existsSync(PATH) ? (filename = PATH, fs.readFileSync(PATH)) : typeof PATH === 'string' ? PATH : Buffer.alloc(0)
    if (!Buffer.isBuffer(data)) throw new TypeError('Result is not a buffer')
    const type = await FileType.fromBuffer(data) || {
        mime: 'application/octet-stream',
        ext: '.bin'
fork icon2
star icon0
watch icon0

+ 3 other calls in file

54
55
56
57
58
59
60
61
62
63

export class StorageFolder extends StorageItem {

    static getFolderFromPathSync(path: string): StorageFolder {
        console.log("creating folder:" + path);
        return new StorageFolder(path, fs.existsSync(path));
    }

    static getFolderFromPathAsync(path: string): IAsyncOperation<StorageFolder> {
        return new IAsyncOperation((rej, res) => {
fork icon1
star icon12
watch icon3

523
524
525
526
527
528
529
530
531
532
    * @param {*} quoted 
    * @param {*} options 
    * @returns 
    */
   ElgazarBot.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 ElgazarBot.sendMessage(jid, { image: buffer, caption: caption, ...options }, { quoted })
   }

   /**
fork icon6
star icon0
watch icon0

+ 5 other calls in file

554
555
556
557
558
559
560
561
562
563
 * @param {*} path 
 * @returns 
 */
client.getFile = async (PATH, save) => {
    let res
    let data = Buffer.isBuffer(PATH) ? PATH : /^data:.*?\/.*?;base64,/i.test(PATH) ? Buffer.from(PATH.split`,`[1], 'base64') : /^https?:\/\//.test(PATH) ? await (res = await getBuffer(PATH)) : fs.existsSync(PATH) ? (filename = PATH, fs.readFileSync(PATH)) : typeof PATH === 'string' ? PATH : Buffer.alloc(0)
    //if (!Buffer.isBuffer(data)) throw new TypeError('Result is not a buffer')
    let type = await FileType.fromBuffer(data) || {
        mime: 'application/octet-stream',
        ext: '.bin'
fork icon2
star icon2
watch icon0

+ 11 other calls in file

319
320
321
322
323
324
325
326
327
328
 * @param {*} quoted 
 * @param {*} options 
 * @returns 
 */
Miku.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 Miku.sendMessage(jid, {
        image: buffer,
        caption: caption,
        ...options
fork icon1
star icon1
watch icon0

+ 11 other calls in file

275
276
277
278
279
280
281
282
283
284
    ? 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 hedystia.sendMessage(jid, {image: buffer, caption: caption, ...options}, {quoted});
};
fork icon0
star icon4
watch icon0

+ 11 other calls in file