fs#statSync JavaScript Examples

The following examples show how to use fs#statSync. 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: main.js    From HinataMd with GNU General Public License v3.0 6 votes vote down vote up
function clearTmp() {
  const tmp = [tmpdir(), join(__dirname, './tmp')]
  const filename = []
  tmp.forEach(dirname => readdirSync(dirname).forEach(file => filename.push(join(dirname, file))))
  return filename.map(file => {
    const stats = statSync(file)
    if (stats.isFile() && (Date.now() - stats.mtimeMs >= 1000 * 60 * 3)) return unlinkSync(file) // 3 minutes
    return false
  })
}
Example #2
Source File: owner-cleartmp.js    From HinataMd with GNU General Public License v3.0 6 votes vote down vote up
handler = async (m, { conn, usedPrefix: _p, __dirname, args }) => {

conn.reply(m.chat, 'Succes !', m)

const tmp = [tmpdir(), join(__dirname, '../tmp')]
  const filename = []
  tmp.forEach(dirname => readdirSync(dirname).forEach(file => filename.push(join(dirname, file))))
  return filename.map(file => {
    const stats = statSync(file)
    unlinkSync(file)
})
}
Example #3
Source File: optimizeSvg.js    From fes.js with MIT License 6 votes vote down vote up
export default function optimizeSvg(files) {
    const optimizedSvgData = [];
    for (const filePath of files) {
        if (statSync(filePath).isFile() && extname(filePath) === '.svg') {
            const data = readFileSync(filePath, 'utf-8');
            const svgData = optimize(data, { path: filePath, plugins: presetDefault });
            optimizedSvgData.push({
                fileName: basename(filePath),
                ...svgData
            });
        }
    }
    return Promise.all(optimizedSvgData);
}
Example #4
Source File: helper.js    From fes.js with MIT License 6 votes vote down vote up
/**
 * 获取文件夹所有JS文件路径
 * @param {string} dir
 */
function getDirFilePaths(dir) {
    const dirs = readdirSync(dir);
    let pathList = [];
    for (const name of dirs) {
        const path = winPath(join(dir, name));
        const info = statSync(path);
        if (info.isDirectory()) {
            pathList = pathList.concat(getDirFilePaths(path));
        } else if (path.endsWith('.js')) {
            pathList.push(path);
        }
    }
    return pathList;
}
Example #5
Source File: helper.js    From fes.js with MIT License 6 votes vote down vote up
/**
 * 获取文件夹所有JS文件路径
 * @param {string} dir
 */
function getDirFilePaths(dir) {
    const dirs = readdirSync(dir);
    let pathList = [];
    for (const name of dirs) {
        const path = winPath(join(dir, name));
        const info = statSync(path);
        if (info.isDirectory()) {
            pathList = pathList.concat(getDirFilePaths(path));
        } else if (path.endsWith('.js')) {
            pathList.push(path);
        }
    }
    return pathList;
}
Example #6
Source File: Generator.js    From fes.js with MIT License 6 votes vote down vote up
copyDirectory(opts) {
      const files = glob.sync('**/*', {
          cwd: opts.path,
          dot: true,
          ignore: ['**/node_modules/**']
      });
      files.forEach((file) => {
          const absFile = join(opts.path, file);
          if (statSync(absFile).isDirectory()) return;
          if (file.endsWith('.tpl')) {
              this.copyTpl({
                  templatePath: absFile,
                  target: join(opts.target, file.replace(/\.tpl$/, '')),
                  context: opts.context
              });
          } else {
              console.log(`${chalk.green('Copy: ')} ${file}`);
              const absTarget = join(opts.target, file);
              mkdirp.sync(dirname(absTarget));
              copyFileSync(absFile, absTarget);
          }
      });
  }
Example #7
Source File: installer.js    From setup-graalvm with MIT License 6 votes vote down vote up
decompressDownload = async (compressedFile, compressedFileExtension, destinationDir) => {
    await mkdirP(destinationDir);

    const graalvmFile = normalize(compressedFile);
    const stats       = statSync(graalvmFile);

    if (stats) {
        if (stats.isFile()) {
            await extractFiles(graalvmFile, compressedFileExtension, destinationDir);

            return join(destinationDir, readdirSync(destinationDir)[0]);
        } else {
            throw new Error(`Failed to extract ${graalvmFile} which is not a file`);
        }
    } else {
        throw new Error(`${graalvmFile} does not exist`);
    }
}
Example #8
Source File: installer.js    From setup-graalvm with MIT License 6 votes vote down vote up
extractFiles = async (compressedFile, compressedFileExtension, destinationDir) => {
    const stats = statSync(compressedFile);
    if (stats) {
        if (stats.isFile()) {
            if ('.tar' === compressedFileExtension || '.tar.gz' === compressedFileExtension) {
                await extractTar(compressedFile, destinationDir);
            } else if ('.zip' === compressedFileExtension) {
                await extractZip(compressedFile, destinationDir);
            } else {
                throw new Error(`Failed to extract ${compressedFile} which is in an unrecognized compression format`);
            }
        } else {
            throw new Error(`Failed to extract ${compressedFile} which is not a file`);
        }
    } else {
        throw new Error(`${compressedFile} does not exist`);
    }
}
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: index.js    From kit with MIT License 6 votes vote down vote up
/**
 * @param {string} file
 * @param {'gz' | 'br'} format
 */
async function compress_file(file, format = 'gz') {
	const compress =
		format == 'br'
			? zlib.createBrotliCompress({
					params: {
						[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
						[zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
						[zlib.constants.BROTLI_PARAM_SIZE_HINT]: statSync(file).size
					}
			  })
			: zlib.createGzip({ level: zlib.constants.Z_BEST_COMPRESSION });

	const source = createReadStream(file);
	const destination = createWriteStream(`${file}.${format}`);

	await pipe(source, compress, destination);
}
Example #11
Source File: index.js    From kit with MIT License 6 votes vote down vote up
/**
 * @param {string} file
 * @param {'gz' | 'br'} format
 */
async function compress_file(file, format = 'gz') {
	const compress =
		format == 'br'
			? zlib.createBrotliCompress({
					params: {
						[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
						[zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
						[zlib.constants.BROTLI_PARAM_SIZE_HINT]: statSync(file).size
					}
			  })
			: zlib.createGzip({ level: zlib.constants.Z_BEST_COMPRESSION });

	const source = createReadStream(file);
	const destination = createWriteStream(`${file}.${format}`);

	await pipe(source, compress, destination);
}
Example #12
Source File: getPaths.js    From fes.js with MIT License 5 votes vote down vote up
function isDirectoryAndExist(path) {
    return existsSync(path) && statSync(path).isDirectory();
}
Example #13
Source File: index.js    From fes.js with MIT License 5 votes vote down vote up
isProcessFile = function (path) {
    const ext = extname(path);
    return statSync(path).isFile() && ['.vue', '.jsx', '.tsx'].includes(ext);
}
Example #14
Source File: index.js    From fes.js with MIT License 5 votes vote down vote up
isProcessDirectory = function (path, item) {
    const component = join(path, item);
    return statSync(component).isDirectory() && !['components'].includes(item);
}
Example #15
Source File: send-file.js    From nanoexpress with Apache License 2.0 5 votes vote down vote up
export default function sendFile(
  path,
  lastModified = true,
  compressed = false
) {
  const req = this.__request;
  const { headers } = req;
  const responseHeaders = {};

  const stat = statSync(path);
  let { size } = stat;

  // handling last modified
  if (lastModified) {
    const { mtime } = stat;

    mtime.setMilliseconds(0);
    const mtimeutc = mtime.toUTCString();

    // Return 304 if last-modified
    if (headers && headers['if-modified-since']) {
      if (new Date(headers['if-modified-since']) >= mtime) {
        this.writeStatus('304 Not Modified');
        return this.end();
      }
    }
    responseHeaders['last-modified'] = mtimeutc;
  }
  responseHeaders['content-type'] = getMime(path);

  // write data
  let start = 0;
  let end = 0;

  if (headers && headers.range) {
    [start, end] = headers.range
      .substr(6)
      .split('-')
      .map((byte) => (byte ? parseInt(byte, 10) : undefined));

    // Chrome patch for work
    if (end === undefined) {
      end = size - 1;
    }

    if (start !== undefined) {
      this.writeStatus('206 Partial Content');
      responseHeaders['accept-ranges'] = 'bytes';
      responseHeaders['content-range'] = `bytes ${start}-${end}/${size}`;
      size = end - start + 1;
    }
  }

  // for size = 0
  if (end < 0) {
    end = 0;
  }

  req.responseHeaders = responseHeaders;

  const createStreamInstance = end
    ? createReadStream(path, { start, end })
    : createReadStream(path);

  const pipe = this.pipe(createStreamInstance, size, compressed);
  this.writeHeaders(responseHeaders);

  return pipe;
}
Example #16
Source File: registerMethods.js    From fes.js with MIT License 4 votes vote down vote up
export default function (api) {
    [
        'onExit',
        'onGenerateFiles',
        'addPluginExports',
        'addCoreExports',
        'addRuntimePluginKey',
        'addRuntimePlugin',
        'addEntryImportsAhead',
        'addEntryImports',
        'addEntryCodeAhead',
        'addEntryCode',
        'addBeforeMiddlewares',
        'addHTMLHeadScripts',
        'addMiddlewares',
        'modifyRoutes',
        'modifyBundleConfigOpts',
        'modifyBundleConfig',
        'modifyBabelOpts',
        'modifyBabelPresetOpts',
        'chainWebpack',
        'addTmpGenerateWatcherPaths',
        'modifyPublicPathStr'
    ].forEach((name) => {
        api.registerMethod({ name });
    });

    api.registerMethod({
        name: 'writeTmpFile',
        fn({
            path,
            content
        }) {
            assert(
                api.stage >= api.ServiceStage.pluginReady,
                'api.writeTmpFile() should not execute in register stage.'
            );
            const absPath = join(api.paths.absTmpPath, path);
            api.utils.mkdirp.sync(dirname(absPath));
            if (!existsSync(absPath) || readFileSync(absPath, 'utf-8') !== content) {
                writeFileSync(absPath, content, 'utf-8');
            }
        }
    });

    api.registerMethod({
        name: 'copyTmpFiles',
        fn({
            namespace, path, ignore
        }) {
            assert(
                api.stage >= api.ServiceStage.pluginReady,
                'api.copyTmpFiles() should not execute in register stage.'
            );
            assert(
                path,
                'api.copyTmpFiles() should has param path'
            );
            assert(
                namespace,
                'api.copyTmpFiles() should has param namespace'
            );
            const files = api.utils.glob.sync('**/*', {
                cwd: path
            });
            const base = join(api.paths.absTmpPath, namespace);
            files.forEach((file) => {
                const source = join(path, file);
                const target = join(base, file);
                if (!existsSync(dirname(target))) {
                    api.utils.mkdirp.sync(dirname(target));
                }
                if (statSync(source).isDirectory()) {
                    api.utils.mkdirp.sync(target);
                } else if (Array.isArray(ignore)) {
                    if (!ignore.some(pattern => new RegExp(pattern).test(file))) {
                        copyFileSync(source, target);
                    }
                } else {
                    copyFileSync(source, target);
                }
            });
        }
    });
}