fs#existsSync JavaScript Examples

The following examples show how to use fs#existsSync. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: buildDevUtils.js    From fes.js with MIT License 6 votes vote down vote up
export function cleanTmpPathExceptCache({
    absTmpPath
}) {
    if (!existsSync(absTmpPath)) return;
    readdirSync(absTmpPath).forEach((file) => {
        if (file === '.cache') return;
        rimraf.sync(join(absTmpPath, file));
    });
}
Example #2
Source File: index.js    From watchlist with MIT License 6 votes vote down vote up
export async function watch(list, callback, opts={}) {
	const cwd = resolve('.', opts.cwd || '.');
	const dirs = new Set(list.map(str => resolve(cwd, str)).filter(existsSync));
	const ignores = ['node_modules'].concat(opts.ignore || []).map(x => new RegExp(x, 'i'));

	let wip = 0;
	const Triggers = new Set;
	const Watchers = new Map;

	async function handle() {
		await callback();
		if (--wip) return handle();
	}

	// TODO: Catch `EPERM` on Windows for removed dir
	async function onChange(dir, type, filename) {
		if (ignores.some(x => x.test(filename))) return;

		let tmp = join(dir, filename);
		if (Triggers.has(tmp)) return;
		if (wip++) return wip = 1;

		if (opts.clear) console.clear();

		Triggers.add(tmp);
		await handle();
		Triggers.delete(tmp);
	}

	let dir, output, key;
	for (dir of dirs) {
		output = await setup(dir, onChange);
		for (key in output) Watchers.set(key, output[key]);
	}

	if (opts.eager) {
		await callback();
	}
}
Example #3
Source File: editor.js    From ReactSourceCodeAnalyze with MIT License 6 votes vote down vote up
export function getValidFilePath(
  maybeRelativePath: string,
  absoluteProjectRoots: Array<string>,
): string | null {
  // We use relative paths at Facebook with deterministic builds.
  // This is why our internal tooling calls React DevTools with absoluteProjectRoots.
  // If the filename is absolute then we don't need to care about this.
  if (isAbsolute(maybeRelativePath)) {
    if (existsSync(maybeRelativePath)) {
      return maybeRelativePath;
    }
  } else {
    for (let i = 0; i < absoluteProjectRoots.length; i++) {
      const projectRoot = absoluteProjectRoots[i];
      const joinedPath = join(projectRoot, maybeRelativePath);
      if (existsSync(joinedPath)) {
        return joinedPath;
      }
    }
  }

  return null;
}
Example #4
Source File: rollup.config.js    From use-shopping-cart with MIT License 6 votes vote down vote up
/**
 * Deletes the dist/ folder and then makes a new directory.
 * Equivalent to `rm -r dist && mkdir dist`
 */
function clearDist() {
  let cleared = false

  return {
    async buildStart() {
      if (cleared) return
      cleared = true

      try {
        if (existsSync(path.resolve('dist')))
          await fs.rm(path.resolve('dist'), { recursive: true })

        await fs.mkdir(path.resolve('dist'))
        console.log('Cleared dist/ folder.')
      } catch (error) {
        console.error('Unable to clear dist/ folder.')
        console.error(error)
      }
    }
  }
}
Example #5
Source File: lint-versions.js    From rocket with MIT License 6 votes vote down vote up
function readPackageJsonNameVersion(filePath) {
  if (existsSync(filePath)) {
    const jsonData = JSON.parse(readFileSync(filePath, 'utf-8'));
    const result = {};
    result[jsonData.name] = `^${jsonData.version}`;
    return result;
  }
  return {};
}
Example #6
Source File: lint-versions.js    From rocket with MIT License 6 votes vote down vote up
function readPackageJsonDeps(filePath) {
  if (existsSync(filePath)) {
    const jsonData = JSON.parse(readFileSync(filePath, 'utf-8'));
    const merged = { ...jsonData.dependencies, ...jsonData.devDependencies };
    const result = {};
    Object.keys(merged).forEach(dep => {
      if (merged[dep] && !merged[dep].includes('file:')) {
        result[dep] = merged[dep];
      }
    });
    return result;
  }
  return {};
}
Example #7
Source File: configHelpers.js    From twin.macro with MIT License 6 votes vote down vote up
getTailwindConfigProperties = (state, config) => {
  const sourceRoot = state.file.opts.sourceRoot || '.'
  const configFile = config && config.config

  const baseDir = state.filename ? dirname(state.filename) : process.cwd()

  const configPath = configFile
    ? resolve(sourceRoot, configFile)
    : escalade(baseDir, (_dir, names) => {
        if (names.includes('tailwind.config.js')) {
          return 'tailwind.config.js'
        }

        if (names.includes('tailwind.config.cjs')) {
          return 'tailwind.config.cjs'
        }
      })

  const configExists = configPath && existsSync(configPath)

  const configSelected = configExists
    ? requireFresh(configPath)
    : defaultTailwindConfig

  const configUser = silenceContentWarning(configSelected)
  const tailwindConfig = resolveTailwindConfig([...getAllConfigs(configUser)])

  throwIf(!tailwindConfig, () =>
    logGeneralError(`Couldn’t find the Tailwind config.\nLooked in ${config}`)
  )

  return { configExists, tailwindConfig, configPath }
}
Example #8
Source File: getAppEntryPath.js    From fes.js with MIT License 6 votes vote down vote up
export function getAppPath(absSrcPath) {
    for (const suffix of ['.js', '.ts', '.jsm', '.jsx', '.tsx']) {
        const p = winPath(join(absSrcPath, `app${suffix}`));
        if (existsSync(p)) {
            return p;
        }
    }
    return null;
}
Example #9
Source File: outbox-store.js    From medusa with MIT License 6 votes vote down vote up
getSize() {
    if (!existsSync(this.bufferFilePath)) {
      return 0
    }

    try {
      const stats = statSync(this.bufferFilePath)
      return stats.size
    } catch (e) {
      if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
        console.error("Failed to get outbox size", e)
      }
    }
    return 0
  }
Example #10
Source File: outbox-store.js    From medusa with MIT License 6 votes vote down vote up
getCount() {
    if (!existsSync(this.bufferFilePath)) {
      return 0
    }

    try {
      const fileBuffer = readFileSync(this.bufferFilePath)
      const str = fileBuffer.toString()
      const lines = str.split("\n")
      return lines.length - 1
    } catch (e) {
      if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
        console.error("Failed to get outbox count", e)
      }
    }
    return 0
  }
Example #11
Source File: outbox-store.js    From medusa with MIT License 6 votes vote down vote up
async flushFile(filePath, flushOperation) {
    const now = `${Date.now()}-${process.pid}`
    let success = false
    let contents = ``
    try {
      if (!existsSync(filePath)) {
        return true
      }
      // Unique temporary file name across multiple concurrent Medusa instances
      const newPath = `${this.bufferFilePath}-${now}`
      renameSync(filePath, newPath)
      contents = readFileSync(newPath, `utf8`)
      unlinkSync(newPath)

      // There is still a chance process dies while sending data and some events are lost
      // This will be ok for now, however
      success = await flushOperation(contents)
    } catch (e) {
      if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
        console.error("Failed to perform file flush", e)
      }
    } finally {
      // if sending fails, we write the data back to the log
      if (!success) {
        if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
          console.error(
            "File flush did not succeed - writing back to file",
            success
          )
        }
        this.appendToBuffer(contents)
      }
    }
    return true
  }
Example #12
Source File: watchPkg.js    From fes.js with MIT License 6 votes vote down vote up
function getPluginsFromPkgPath(opts) {
    let pkg = {};
    if (existsSync(opts.pkgPath)) {
        try {
            pkg = JSON.parse(readFileSync(opts.pkgPath, 'utf-8'));
        } catch (e) {
            // ignore
        }
    }
    return getPlugins({ pkg });
}
Example #13
Source File: index.js    From kit with MIT License 6 votes vote down vote up
function get_netlify_config() {
	if (!existsSync('netlify.toml')) return null;

	try {
		return /** @type {NetlifyConfig} */ (toml.parse(readFileSync('netlify.toml', 'utf-8')));
	} catch (err) {
		err.message = `Error parsing netlify.toml: ${err.message}`;
		throw err;
	}
}
Example #14
Source File: loadDotEnv.js    From fes.js with MIT License 6 votes vote down vote up
/**
 * dotenv wrapper
 * @param envPath string
 */
export default function loadDotEnv(envPath) {
    if (existsSync(envPath)) {
        const parsed = parse(readFileSync(envPath, 'utf-8')) || {};
        Object.keys(parsed).forEach((key) => {
            // eslint-disable-next-line no-prototype-builtins
            process.env[key] = parsed[key];
        });
    }
}
Example #15
Source File: index.js    From kit with MIT License 6 votes vote down vote up
/**
 * @param {string} directory
 */
async function compress(directory) {
	if (!existsSync(directory)) {
		return;
	}

	const files = await glob('**/*.{html,js,json,css,svg,xml,wasm}', {
		cwd: directory,
		dot: true,
		absolute: true,
		filesOnly: true
	});

	await Promise.all(
		files.map((file) => Promise.all([compress_file(file, 'gz'), compress_file(file, 'br')]))
	);
}
Example #16
Source File: server.js    From asymptoteWebApplication with GNU Lesser General Public License v3.0 6 votes vote down vote up
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    Iframe Request
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
app.use("/clients", (req, res, next) => {
  if (req.method === "GET") {
    const fileToServe = __dirname + req.originalUrl;
    if (existsSync(fileToServe)) {
      createReadStream(fileToServe).pipe(res);
    }
  } else {
    next();
  }
});
Example #17
Source File: index.js    From fes.js with MIT License 6 votes vote down vote up
getWatchFilesAndDirectories() {
        const fesEnv = process.env.FES_ENV;
        const configFiles = lodash.clone(CONFIG_FILES);
        CONFIG_FILES.forEach((f) => {
            if (this.localConfig) configFiles.push(this.addAffix(f, 'local'));
            if (fesEnv) configFiles.push(this.addAffix(f, fesEnv));
        });

        const configDir = winPath(join(this.cwd, 'config'));

        const files = configFiles
            .reduce((memo, f) => {
                const file = winPath(join(this.cwd, f));
                if (existsSync(file)) {
                    memo = memo.concat(parseRequireDeps(file));
                } else {
                    memo.push(file);
                }
                return memo;
            }, [])
            .filter(f => !f.startsWith(configDir));

        return [configDir].concat(files);
    }
Example #18
Source File: index.js    From fes.js with MIT License 6 votes vote down vote up
getConfigFile() {
        // TODO: support custom config file
        let configFile = CONFIG_FILES.find(f => existsSync(join(this.cwd, f)));
        if (!configFile) return [];
        configFile = winPath(configFile);
        let envConfigFile;
        // 潜在问题:
        // .local 和 .env 的配置必须有 configFile 才有效
        if (process.env.FES_ENV) {
            envConfigFile = this.addAffix(
                configFile,
                process.env.FES_ENV
            );
            if (!existsSync(join(this.cwd, envConfigFile))) {
                throw new Error(
                    `get user config failed, ${envConfigFile} does not exist, but process.env.FES_ENV is set to ${process.env.FES_ENV}.`
                );
            }
        }
        const files = [
            configFile,
            envConfigFile,
            this.localConfig && this.addAffix(configFile, 'local')
        ]
            .filter(f => !!f)
            .map(f => join(this.cwd, f))
            .filter(f => existsSync(f));
        return files;
    }
Example #19
Source File: modules.js    From Kadena-Mining-Stratum with GNU General Public License v2.0 6 votes vote down vote up
/** Extract information about package.json modules */
function collectModules() {
    var mainPaths = (require.main && require.main.paths) || [];
    var paths = require.cache ? Object.keys(require.cache) : [];
    var infos = {};
    var seen = {};
    paths.forEach(function (path) {
        var dir = path;
        /** Traverse directories upward in the search of package.json file */
        var updir = function () {
            var orig = dir;
            dir = dirname(orig);
            if (!dir || orig === dir || seen[orig]) {
                return undefined;
            }
            if (mainPaths.indexOf(dir) < 0) {
                return updir();
            }
            var pkgfile = join(orig, 'package.json');
            seen[orig] = true;
            if (!existsSync(pkgfile)) {
                return updir();
            }
            try {
                var info = JSON.parse(readFileSync(pkgfile, 'utf8'));
                infos[info.name] = info.version;
            }
            catch (_oO) {
                // no-empty
            }
        };
        updir();
    });
    return infos;
}
Example #20
Source File: serverAnalyzer.js    From asymptoteWebApplication with GNU Lesser General Public License v3.0 6 votes vote down vote up
// ------------------------------------------------
export function delAnalyzer(serverDir) {
  return (req, res, next) => {
    let requestAndId = /(\w+)&(\w+)/gi.exec(req.body);
    if (requestAndId[1] === "deleteReq") {
      const reqDest = usrDirMgr(req, serverDir, requestAndId[2]);
      if (existsSync(reqDest.usrAbsDirPath)) {
        removeDir(reqDest.usrAbsDirPath);
      } else {
        res.send(null);
      }
    } else {
      res.send(null);
    }
  }
}
Example #21
Source File: main.js    From HinataMd with GNU General Public License v3.0 6 votes vote down vote up
global.reload = async (_ev, filename) => {
  if (pluginFilter(filename)) {
    let dir = global.__filename(join(pluginFolder, filename), true)
    if (filename in global.plugins) {
      if (existsSync(dir)) conn.logger.info(` updated plugin - '${filename}'`)
      else {
        conn.logger.warn(`deleted plugin - '${filename}'`)
        return delete global.plugins[filename]
      }
    } else conn.logger.info(`new plugin - '${filename}'`)
    let err = syntaxerror(readFileSync(dir), filename, {
      sourceType: 'module',
      allowAwaitOutsideFunction: true
    })
    if (err) conn.logger.error(`syntax error while loading '${filename}'\n${format(err)}`)
    else try {
      const module = (await import(`${global.__filename(dir)}?update=${Date.now()}`))
      global.plugins[filename] = module.default || module
    } catch (e) {
      conn.logger.error(`error require plugin '${filename}\n${format(e)}'`)
    } finally {
      global.plugins = Object.fromEntries(Object.entries(global.plugins).sort(([a], [b]) => a.localeCompare(b)))
    }
  }
}
Example #22
Source File: serverAnalyzer.js    From asymptoteWebApplication with GNU Lesser General Public License v3.0 6 votes vote down vote up
// ------------------------------------------------
export function downloadReq(dirname) {
  return function (req, res, next) {
    if (req.body.codeOption) {
      if (existsSync(req.body.codeFilePath)) {
        res.download(req.body.codeFilePath);
      }
    }
    if (req.body.outputOption) {
      const outputFilePath = req.body.usrAbsDirPath + "/" + req.body.codeFilename + "." + req.body.requestedOutformat;
      if (existsSync(outputFilePath)) {
        res.download(outputFilePath);
      }
    }
  }
}
Example #23
Source File: index.js    From kit with MIT License 5 votes vote down vote up
/**
 * @param {import('@sveltejs/kit').Builder} builder
 * @returns {WranglerConfig}
 */
function validate_config(builder) {
	if (existsSync('wrangler.toml')) {
		/** @type {WranglerConfig} */
		let wrangler_config;

		try {
			wrangler_config = /** @type {WranglerConfig} */ (
				toml.parse(readFileSync('wrangler.toml', 'utf-8'))
			);
		} catch (err) {
			err.message = `Error parsing wrangler.toml: ${err.message}`;
			throw err;
		}

		if (!wrangler_config.site?.bucket) {
			throw new Error(
				'You must specify site.bucket in wrangler.toml. Consult https://developers.cloudflare.com/workers/platform/sites/configuration'
			);
		}

		if (!wrangler_config.main) {
			throw new Error(
				'You must specify main option in wrangler.toml. Consult https://github.com/sveltejs/kit/tree/master/packages/adapter-cloudflare-workers'
			);
		}

		return wrangler_config;
	}

	builder.log.error(
		'Consult https://developers.cloudflare.com/workers/platform/sites/configuration on how to setup your site'
	);

	builder.log(
		`
		Sample wrangler.toml:

		name = "<your-site-name>"
		account_id = "<your-account-id>"

		main = "./.cloudflare/worker.js"
		site.bucket = "./.cloudflare/public"

		build.command = "npm run build"

		compatibility_date = "2021-11-12"
		workers_dev = true`
			.replace(/^\t+/gm, '')
			.trim()
	);

	throw new Error('Missing a wrangler.toml file');
}
Example #24
Source File: serverAnalyzer.js    From asymptoteWebApplication with GNU Lesser General Public License v3.0 5 votes vote down vote up
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    Resolver core function
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function asyRunManager(req, res, next, option) {
  const asyArgs = ['-noV', '-outpipe', '2', '-noglobalread', '-f', option.outformat, option.codeFile];
  const chProcOption = {
    cwd: option.cwd,
  }
  const htmlFileExists = existsSync(req.body.htmlFile);
  // if (req.body.reqType === "download" && option.outformat === "html" && htmlFileExists) {
  //   res.send({
  //     responseType: FLAGS.SUCCESS.ASY_OUTPUT_CREATED,
  //     isUpdated: !req.body.isUpdated
  //   });
  //   return;
  // }
  if (htmlFileExists) {
    unlinkSync(req.body.htmlFile);
  }
  let stderrData = "", stdoutData = "";
  const chProcHandler = spawn('asy', asyArgs, chProcOption);
  setTimeout(() => {
    chProcHandler.kill("SIGTERM");
  }, serverTimeout)
  // ------------------------------- onError
  chProcHandler.on('error', (err) => {
    const errResObject = errResCreator(FLAGS.FAILURE.PROCESS_SPAWN_ERR, err);
    chProcHandler.kill();
    res.send(errResObject);
  });
  // ------------------------------- onData
  chProcHandler.stderr.on('data', (chunk) => {stderrData += chunk.toString()});
  chProcHandler.stdout.on('data', (chunk) => {stdoutData += chunk.toString()});
  // ------------------------------- onClose
  chProcHandler.on('close', () => {});
  // ------------------------------- onExit
  chProcHandler.on('exit', (code, signal) => {
    if (code === null) {
      (signal === "SIGTERM") ? res.send(errResCreator(FLAGS.FAILURE.PROCESS_TIMEDOUT_ERR)) :
          res.send(errResCreator(FLAGS.FAILURE.PROCESS_TERMINATED_ERR));
    } else if (code !== 0) {
      res.send({
        ...errResCreator(FLAGS.FAILURE.ASY_CODE_COMPILE_ERR),
        stderr: stderrData,
        stdout: stdoutData,
        isUpdated: false
      });
    } else {
      process.nextTick(() => {
        const outputFilePath = req.body.usrAbsDirPath + "/" + req.body.codeFilename + "." + option.outformat;
        if (existsSync(outputFilePath)) {
          res.send({
            responseType: FLAGS.SUCCESS.ASY_OUTPUT_CREATED,
            stderr: stderrData,
            stdout: stdoutData,
            isUpdated: !req.body.isUpdated,
            path: (option.outformat === "html")? req.body.usrRelDirPath
                + "/" + req.body.codeFilename + "." + option.outformat: ""
          });
        } else {
          res.send({
            responseType: FLAGS.SUCCESS.ASY_RUN_NO_OUTPUT,
            stderr: stderrData,
            stdout: stdoutData,
            isUpdated: false
          });
        }
      });
    }
    // console.log(`Code: ${code}\nSignal: ${signal}`);
  });
}
Example #25
Source File: aem-component-loader.js    From aem with MIT License 5 votes vote down vote up
getRequiredHTL = (logger, component, context, pathBaseName) => {
  const htlFile = `${context.split(pathSeparator).join('/')}/${pathBaseName}.html`;
  if (!existsSync(`${htlFile}`)) {
    logger.info(`No HTL script for ${pathBaseName}`);
    return '';
  }
  return `component.module = require('${htlFile}');`;
}
Example #26
Source File: main.js    From k-domains with MIT License 5 votes vote down vote up
export default function(options) {
  const routerFile = path.join(this.options.srcDir, "router.js");
  if( !existsSync(routerFile) ){
    logger.info(new Error("router.js file not found"));
    logger.info(`creating new router configuration in ${this.options.srcDir}`)
    copyFileSync(path.join(__dirname, "router.js"), routerFile);
  }
 }
Example #27
Source File: database.js    From HinataMd with GNU General Public License v3.0 5 votes vote down vote up
_load() {
        try {
          return this._data = existsSync(this.file) ? JSON.parse(readFileSync(this.file)) : {}
        } catch (e) {
          this.logger.error(e)
          return this._data = {}
        }
    }
Example #28
Source File: configHelpers.js    From twin.macro with MIT License 5 votes vote down vote up
checkExists = (fileName, sourceRoot) => {
  const [, value] = getFirstValue(toArray(fileName), fileName =>
    existsSync(resolve(sourceRoot, `./${fileName}`))
  )
  return value
}
Example #29
Source File: index.js    From fes.js with MIT License 5 votes vote down vote up
export default function (api) {
    const { utils: { mergeConfig }, cwd } = api;

    api.registerCommand({
        command: 'test',
        description: 'run unit tests with jest',
        options: getCommandOptiton(),
        async fn({ args }) {
            process.env.NODE_ENV = 'test';

            if (args._[0] === 'test') {
                args._.shift();
            }

            args.debug && logger.log(`args: ${JSON.stringify(args)}`);

            // Read config from cwd/jest.config.js
            const userJestConfigFile = join(cwd, 'jest.config.js');
            const userJestConfig = existsSync(userJestConfigFile) && require(userJestConfigFile);
            args.debug && logger.log(`config from jest.config.js: ${JSON.stringify(userJestConfig)}`);

            // Read jest config from package.json
            const packageJSONPath = join(cwd, 'package.json');
            const packageJestConfig = existsSync(packageJSONPath) && require(packageJSONPath).jest;
            args.debug && logger.log(`jest config from package.json: ${JSON.stringify(packageJestConfig)}`);

            // Merge configs
            // user config and args config could have value function for modification
            const config = mergeConfig(
                createDefaultConfig(cwd, args),
                packageJestConfig,
                userJestConfig
            );
            args.debug && logger.log(`final config: ${JSON.stringify(config)}`);

            // Generate jest options
            const argsConfig = Object.keys(CliOptions).reduce((prev, name) => {
                if (args[name]) prev[name] = args[name];

                // Convert alias args into real one
                const { alias } = CliOptions[name];
                if (alias && args[alias]) prev[name] = args[alias];
                return prev;
            }, {});
            args.debug && logger.log(`config from args: ${JSON.stringify(argsConfig)}`);

            // 比较大的库建议使用require,使用时才加载,提升fes命令的效率
            const { runCLI } = require('jest');
            // Run jest
            const result = await runCLI(
                {
                    // @ts-ignore
                    _: args._ || [],
                    // @ts-ignore
                    $0: args.$0 || '',
                    // 必须是单独的 config 配置,值为 string,否则不生效
                    // @ts-ignore
                    config: JSON.stringify(config),
                    ...argsConfig
                },
                [cwd]
            );
            args.debug && logger.log(result);

            // Throw error when run failed
            assert(result.results.success, 'Test with jest failed');
        }
    });
}