fs#readdirSync JavaScript Examples

The following examples show how to use fs#readdirSync. 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
async function filesInit() {
  for (let filename of readdirSync(pluginFolder).filter(pluginFilter)) {
    try {
      let file = global.__filename(join(pluginFolder, filename))
      const module = await import(file)
      global.plugins[filename] = module.default || module
    } catch (e) {
      conn.logger.error(e)
      delete global.plugins[filename]
    }
  }
}
Example #2
Source File: filesystem.spec.js    From kit with MIT License 6 votes vote down vote up
suite_copy('copies recursively', () => {
	write('file-one.js', '');
	write('file-two.css', '');
	write('deep/a.js', '');
	write('deep/b.js', '');

	copy(source_dir, dest_dir);

	const root = readdirSync(dest_dir);

	assert.equal(root.sort(), ['file-one.js', 'file-two.css', 'deep'].sort());

	const subdir = readdirSync(join(dest_dir, 'deep'));

	assert.equal(subdir.sort(), ['a.js', 'b.js'].sort());
});
Example #3
Source File: filesystem.spec.js    From kit with MIT License 6 votes vote down vote up
suite_copy('filters out subdirectory contents', () => {
	write('file-one.js', '');
	write('file-two.css', '');
	write('no-copy/do-not-copy.js', '');

	copy(source_dir, dest_dir, {
		filter: (f) => f !== 'no-copy'
	});

	const copied = readdirSync(dest_dir);

	assert.equal(copied.sort(), ['file-one.js', 'file-two.css'].sort());
});
Example #4
Source File: filesystem.spec.js    From kit with MIT License 6 votes vote down vote up
suite_copy('without filter', () => {
	write('file-one.js', '');
	write('file-two.css', '');
	write('file-three', '');

	copy(source_dir, dest_dir);

	const copied = readdirSync(dest_dir);

	assert.equal(copied.sort(), ['file-one.js', 'file-two.css', 'file-three'].sort());
});
Example #5
Source File: outbox-store.js    From medusa with MIT License 6 votes vote down vote up
async startFlushEvents(flushOperation) {
    try {
      await this.flushFile(this.bufferFilePath, flushOperation)
      const files = readdirSync(this.baseDir)
      const filtered = files.filter(p => p.startsWith(`events.json`))
      for (const file of filtered) {
        await this.flushFile(path.join(this.baseDir, file), flushOperation)
      }
      return true
    } catch (e) {
      if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
        console.error("Failed to perform flush", e)
      }
    }
    return false
  }
Example #6
Source File: i18n.js    From i18next-fs-backend with MIT License 6 votes vote down vote up
i18next
  .use(i18nextMiddleware.LanguageDetector)
  .use(Backend)
  .init({
    // debug: true,
    initImmediate: false, // setting initImediate to false, will load the resources synchronously
    fallbackLng: 'en',
    preload: readdirSync(localesFolder).filter((fileName) => {
      const joinedPath = join(localesFolder, fileName)
      return lstatSync(joinedPath).isDirectory()
    }),
    backend: {
      loadPath: join(localesFolder, '{{lng}}/{{ns}}.json')
    }
  })
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: index.js    From fes.js with MIT License 6 votes vote down vote up
checkHasLayout = function (path) {
    const dirList = readdirSync(path);
    return dirList.some((item) => {
        if (!isProcessFile(join(path, item))) {
            return false;
        }
        const ext = extname(item);
        const fileName = basename(item, ext);
        return fileName === 'layout';
    });
}
Example #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: index.js    From fes.js with MIT License 5 votes vote down vote up
genRoutes = function (parentRoutes, path, parentRoutePath) {
    const dirList = readdirSync(path);
    const hasLayout = checkHasLayout(path);
    const layoutRoute = {
        children: []
    };
    if (hasLayout) {
        layoutRoute.path = parentRoutePath;
        parentRoutes.push(layoutRoute);
    }
    dirList.forEach((item) => {
        // 文件或者目录的绝对路径
        const component = join(path, item);
        if (isProcessFile(component)) {
            const ext = extname(item);
            const fileName = basename(item, ext);
            // 路由的path
            const routePath = getRoutePath(parentRoutePath, fileName);
            if (cacheGenRoutes[routePath]) {
                logger.warn(`[WARNING]: The file path: ${routePath}(.jsx/.tsx/.vue) conflict in router,will only use ${routePath}.tsx or ${routePath}.jsx,please remove one of.`);
                return;
            }
            cacheGenRoutes[routePath] = true;

            // 路由名称
            const routeName = getRouteName(parentRoutePath, fileName);
            const componentPath = posix.join(path, item);

            let content = readFileSync(component, 'utf-8');
            let routeMeta = {};
            if (ext === '.vue') {
                const { descriptor } = parse(content);
                const routeMetaBlock = descriptor.customBlocks.find(
                    b => b.type === 'config'
                );
                routeMeta = routeMetaBlock?.content ? JSON.parse(routeMetaBlock.content) : {};
                if (descriptor.script) {
                    content = descriptor.script.content;
                    routeMeta = getRouteMeta(content) || routeMeta;
                }
            }
            if (ext === '.jsx' || ext === '.tsx') {
                routeMeta = getRouteMeta(content) || {};
            }

            const routeConfig = {
                path: routePath,
                component: componentPath,
                name: routeMeta.name || routeName,
                meta: routeMeta
            };
            if (hasLayout) {
                if (fileName === 'layout') {
                    layoutRoute.component = componentPath;
                } else {
                    layoutRoute.children.push(routeConfig);
                }
            } else {
                parentRoutes.push(routeConfig);
            }
        }
    });

    dirList.forEach((item) => {
        if (isProcessDirectory(path, item)) {
            // 文件或者目录的绝对路径
            const nextPath = join(path, item);
            const nextParentRouteUrl = getRoutePath(parentRoutePath, item, false);
            if (hasLayout) {
                genRoutes(layoutRoute.children, nextPath, nextParentRouteUrl);
            } else {
                genRoutes(parentRoutes, nextPath, nextParentRouteUrl);
            }
        }
    });
}
Example #15
Source File: lint-versions.js    From rocket with MIT License 5 votes vote down vote up
getDirectories = source =>
  readdirSync(source, { withFileTypes: true })
    .filter(pathMeta => pathMeta.isDirectory())
    .map(pathMeta => pathMeta.name)
Example #16
Source File: parse.js    From uvu with MIT License 5 votes vote down vote up
FILES = readdirSync(__dirname)
Example #17
Source File: nulis-hartatahta..js    From HinataMd with GNU General Public License v3.0 5 votes vote down vote up
function ht(text = '') {
    return new Promise((resolve, reject) => {
        let img = join(aesthetic, pickRandom(readdirSync(aesthetic)))
        let font = join(_font, 'Roboto-Black.ttf')
        let w = 1024
        let h = w
        let s = w + 'x' + h
        let xF = `(${noise('X', 2, w, 1)}+${noise('Y', 1, h, 1)})/2+128`
        let yF = `((${pickRandom(['', '-'])}${45 * w / 2048}*${pickRandom(['sin', 'cos'])}(X/${w}*4*PI))+${noise('X', 5, w, 0.8)}+${noise('Y', 2, h, 1)})/1.7+128`
        let fsize = 320 / 2048 * w
        let lh = 1.5
        let format = ''
        let layers = [
            `[v:0]scale=${s}${format}[im]`,
            textArgs('HARTA', 'black', 'white', fsize, font, '(w-text_w)/2', `(h-text_h)/2-(text_h*${lh})`, w, h) + format + '[top]',
            textArgs('TAHTA', 'black', 'white', fsize, font, '(w-text_w)/2', `(h-text_h)/2`, w, h) + format + '[mid]',
            textArgs(text, 'black', 'white', fsize, font, '(w-text_w)/2', `(h-text_h)/2+(text_h*${lh})`, w, h) + format + '[bot]',
            '[top][mid]blend=all_mode=addition[con]',
            '[con][bot]blend=all_mode=addition[txt]',
            `nullsrc=s=${s},geq='r=${xF}:g=${xF}:b=${xF}'[dx]`,
            `nullsrc=s=${s},geq='r=${yF}:g=${yF}:b=${yF}'[dy]`,
            '[txt][dx][dy]displace[wa]',
            '[im][wa]blend=all_mode=multiply:all_opacity=1'
        ]

        let o = 1 * new Date + '_harta_tahta.png'
        o = join(tmp, o)
        let args = [
            '-y',
            '-i', img,
            '-filter_complex', layers.join(';'),
            '-frames:v', '1',
            o
        ]
        
        spawn('ffmpeg', args)
            .on('error', reject)
            .on('close', () => {
                try {
                    resolve(readFileSync(o))
                    unlinkSync(o)
                } catch (e) {
                    reject(e)
                }
            })
        //.stderr.on('data', a => console.log(a+''))
    })
}
Example #18
Source File: build.js    From web-component-plus with Apache License 2.0 5 votes vote down vote up
config = readdirSync(input)
    .filter(name => ![].includes(name))
    .map(name => ({
        input: `${input}/${name}/index.tsx`,
        plugins: [
            terser({
                    output: {
                        comments: false,
                    },
                    numWorkers: cpuNums, //多线程压缩
                }
            ),
            url({
                include: ['**/*.svg', '**/*.png', '**/*.jp(e)?g', '**/*.gif', '**/*.webp', '**/*.ttf', '**/*.woff']
            }),
            nodeResolve(),
            commonjs(),
            postcss({
                name: 'index',
                extensions: [ '.css', 'scss' ],
                to: `${output}/${name}/lib/index.css`,
                plugins: [
                    autoprefixer()
                ],
                // extract: `${output}/${name}/lib/index.css`
                extract: false,
                minimize: true
            }),
            tsPlugin,
            json(),
            replace({
                preventAssignment: true
            })
        ],
        output: [
            { name: name, file: `${output}/${name}/lib/index.umd.js`, format: 'umd' },
            { file: `${output}/${name}/lib/index.cjs.js`, format: 'cjs' },
            { file: `${output}/${name}/lib/index.esm.js`, format: 'es' }

        ]
    }))