path#extname JavaScript Examples
The following examples show how to use
path#extname.
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: xlsxTransform.js From CheatLifeRestart with MIT License | 6 votes |
async function walk(filePath) {
const xlsxPaths = [];
if(Array.isArray(filePath)) {
for(const subPath of filePath)
xlsxPaths.push(await walk(subPath));
return xlsxPaths.flat();
}
const fileStat = await stat(filePath);
if(!fileStat.isDirectory()) {
const ext = extname(filePath);
if( ext=='.xls' || ext=='.xlsx' ) xlsxPaths.push(filePath);
return xlsxPaths;
}
const dirData = await readdir(filePath);
for(const subPath of dirData)
xlsxPaths.push(await walk(join(filePath, subPath)));
return xlsxPaths.flat();
}
Example #2
Source File: optimizeSvg.js From fes.js with MIT License | 6 votes |
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 #3
Source File: index.js From fes.js with MIT License | 6 votes |
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 #4
Source File: index.js From cs-wiki with GNU General Public License v3.0 | 5 votes |
addExtension = function addExtension(filename, ext = '.js') {
let result = `${filename}`;
if (!extname(filename))
result += ext;
return result;
}
Example #5
Source File: index.js From fes.js with MIT License | 5 votes |
addAffix(file, affix) {
const ext = extname(file);
return file.replace(new RegExp(`${ext}$`), `.${affix}${ext}`);
}
Example #6
Source File: pluginUtils.js From fes.js with MIT License | 5 votes |
export function pathToObj({ path, type, cwd }) {
let pkg = null;
let isPkgPlugin = false;
const pkgJSONPath = pkgUp.sync({ cwd: path });
if (pkgJSONPath) {
// eslint-disable-next-line
pkg = require(pkgJSONPath);
isPkgPlugin = winPath(join(dirname(pkgJSONPath), pkg.main || 'index.js'))
=== winPath(path);
}
let id;
if (isPkgPlugin) {
id = pkg.name;
} else if (winPath(path).startsWith(winPath(cwd))) {
id = `./${winPath(relative(cwd, path))}`;
} else if (pkgJSONPath) {
id = winPath(join(pkg.name, relative(dirname(pkgJSONPath), path)));
} else {
id = winPath(path);
}
id = id.replace('@fesjs/preset-built-in/lib/plugins', '@@');
id = id.replace(/\.js$/, '');
const key = isPkgPlugin
? pkgNameToKey(pkg.name, type)
: nameToKey(basename(path, extname(path)));
return {
id,
key,
path: winPath(path),
apply() {
// use function to delay require
try {
// eslint-disable-next-line
const ret = require(path);
// use the default member for es modules
return compatESModuleRequire(ret);
} catch (e) {
throw new Error(`Register ${path} failed, since ${e.message}`);
}
},
defaultConfig: null
};
}
Example #7
Source File: index.js From fes.js with MIT License | 5 votes |
isProcessFile = function (path) {
const ext = extname(path);
return statSync(path).isFile() && ['.vue', '.jsx', '.tsx'].includes(ext);
}
Example #8
Source File: index.js From fes.js with MIT License | 5 votes |
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 #9
Source File: index.js From ucompress with ISC License | 5 votes |
ucompress = (source, dest, options = {}) => {
let method = copy;
switch (extname(source).toLowerCase()) {
case '.css':
method = css;
break;
case '.gif':
method = gif;
break;
case '.html':
/* istanbul ignore next */
case '.htm':
method = html;
break;
case '.jpg':
case '.jpeg':
method = jpg;
break;
case '.js':
case '.mjs':
method = js;
break;
case '.json':
method = json;
break;
case '.md':
method = md;
break;
case '.png':
method = png;
break;
case '.svg':
method = svg;
break;
case '.xml':
method = xml;
break;
}
return method(source, dest, options);
}
Example #10
Source File: index.js From cs-wiki with GNU General Public License v3.0 | 4 votes |
function getPackageInfo(options) {
const {
cache,
extensions,
pkg,
mainFields,
preserveSymlinks,
useBrowserOverrides,
rootDir,
ignoreSideEffectsForRoot
} = options;
let { pkgPath } = options;
if (cache.has(pkgPath)) {
return cache.get(pkgPath);
}
// browserify/resolve doesn't realpath paths returned in its packageFilter callback
if (!preserveSymlinks) {
pkgPath = realpathSync(pkgPath);
}
const pkgRoot = dirname(pkgPath);
const packageInfo = {
// copy as we are about to munge the `main` field of `pkg`.
packageJson: { ...pkg },
// path to package.json file
packageJsonPath: pkgPath,
// directory containing the package.json
root: pkgRoot,
// which main field was used during resolution of this module (main, module, or browser)
resolvedMainField: 'main',
// whether the browser map was used to resolve the entry point to this module
browserMappedMain: false,
// the entry point of the module with respect to the selected main field and any
// relevant browser mappings.
resolvedEntryPoint: ''
};
let overriddenMain = false;
for (let i = 0; i < mainFields.length; i++) {
const field = mainFields[i];
if (typeof pkg[field] === 'string') {
pkg.main = pkg[field];
packageInfo.resolvedMainField = field;
overriddenMain = true;
break;
}
}
const internalPackageInfo = {
cachedPkg: pkg,
hasModuleSideEffects: () => null,
hasPackageEntry: overriddenMain !== false || mainFields.indexOf('main') !== -1,
packageBrowserField:
useBrowserOverrides &&
typeof pkg.browser === 'object' &&
Object.keys(pkg.browser).reduce((browser, key) => {
let resolved = pkg.browser[key];
if (resolved && resolved[0] === '.') {
resolved = resolve(pkgRoot, resolved);
}
/* eslint-disable no-param-reassign */
browser[key] = resolved;
if (key[0] === '.') {
const absoluteKey = resolve(pkgRoot, key);
browser[absoluteKey] = resolved;
if (!extname(key)) {
extensions.reduce((subBrowser, ext) => {
subBrowser[absoluteKey + ext] = subBrowser[key];
return subBrowser;
}, browser);
}
}
return browser;
}, {}),
packageInfo
};
const browserMap = internalPackageInfo.packageBrowserField;
if (
useBrowserOverrides &&
typeof pkg.browser === 'object' &&
// eslint-disable-next-line no-prototype-builtins
browserMap.hasOwnProperty(pkg.main)
) {
packageInfo.resolvedEntryPoint = browserMap[pkg.main];
packageInfo.browserMappedMain = true;
} else {
// index.node is technically a valid default entrypoint as well...
packageInfo.resolvedEntryPoint = resolve(pkgRoot, pkg.main || 'index.js');
packageInfo.browserMappedMain = false;
}
if (!ignoreSideEffectsForRoot || rootDir !== pkgRoot) {
const packageSideEffects = pkg.sideEffects;
if (typeof packageSideEffects === 'boolean') {
internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
} else if (Array.isArray(packageSideEffects)) {
internalPackageInfo.hasModuleSideEffects = createFilter(packageSideEffects, null, {
resolve: pkgRoot
});
}
}
cache.set(pkgPath, internalPackageInfo);
return internalPackageInfo;
}
Example #11
Source File: index.es.js From smart-contracts with MIT License | 4 votes |
function getPackageInfo(options) {
const cache = options.cache,
extensions = options.extensions,
pkg = options.pkg,
mainFields = options.mainFields,
preserveSymlinks = options.preserveSymlinks,
useBrowserOverrides = options.useBrowserOverrides;
let pkgPath = options.pkgPath;
if (cache.has(pkgPath)) {
return cache.get(pkgPath);
} // browserify/resolve doesn't realpath paths returned in its packageFilter callback
if (!preserveSymlinks) {
pkgPath = realpathSync(pkgPath);
}
const pkgRoot = dirname(pkgPath);
const packageInfo = {
// copy as we are about to munge the `main` field of `pkg`.
packageJson: Object.assign({}, pkg),
// path to package.json file
packageJsonPath: pkgPath,
// directory containing the package.json
root: pkgRoot,
// which main field was used during resolution of this module (main, module, or browser)
resolvedMainField: 'main',
// whether the browser map was used to resolve the entry point to this module
browserMappedMain: false,
// the entry point of the module with respect to the selected main field and any
// relevant browser mappings.
resolvedEntryPoint: ''
};
let overriddenMain = false;
for (let i = 0; i < mainFields.length; i++) {
const field = mainFields[i];
if (typeof pkg[field] === 'string') {
pkg.main = pkg[field];
packageInfo.resolvedMainField = field;
overriddenMain = true;
break;
}
}
const internalPackageInfo = {
cachedPkg: pkg,
hasModuleSideEffects: () => null,
hasPackageEntry: overriddenMain !== false || mainFields.indexOf('main') !== -1,
packageBrowserField: useBrowserOverrides && typeof pkg.browser === 'object' && Object.keys(pkg.browser).reduce((browser, key) => {
let resolved = pkg.browser[key];
if (resolved && resolved[0] === '.') {
resolved = resolve(pkgRoot, resolved);
}
/* eslint-disable no-param-reassign */
browser[key] = resolved;
if (key[0] === '.') {
const absoluteKey = resolve(pkgRoot, key);
browser[absoluteKey] = resolved;
if (!extname(key)) {
extensions.reduce((subBrowser, ext) => {
subBrowser[absoluteKey + ext] = subBrowser[key];
return subBrowser;
}, browser);
}
}
return browser;
}, {}),
packageInfo
};
const browserMap = internalPackageInfo.packageBrowserField;
if (useBrowserOverrides && typeof pkg.browser === 'object' && // eslint-disable-next-line no-prototype-builtins
browserMap.hasOwnProperty(pkg.main)) {
packageInfo.resolvedEntryPoint = browserMap[pkg.main];
packageInfo.browserMappedMain = true;
} else {
// index.node is technically a valid default entrypoint as well...
packageInfo.resolvedEntryPoint = resolve(pkgRoot, pkg.main || 'index.js');
packageInfo.browserMappedMain = false;
}
const packageSideEffects = pkg.sideEffects;
if (typeof packageSideEffects === 'boolean') {
internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
} else if (Array.isArray(packageSideEffects)) {
internalPackageInfo.hasModuleSideEffects = createFilter(packageSideEffects, null, {
resolve: pkgRoot
});
}
cache.set(pkgPath, internalPackageInfo);
return internalPackageInfo;
}
Example #12
Source File: index.js From tinyjam with ISC License | 4 votes |
export default function tinyjam(src, dest = src, options = {}) {
options = Object.assign({}, defaultOptions, options);
// Markdown renderer options
const {breaks, smartypants, highlight} = options;
const markedOptions = {breaks, smartypants, highlight, smartLists: true};
const proto = {};
const root = createCtx('.'); // root data object
proto.root = root; // add data root access to all leaf nodes
const templates = [];
const cache = {}; // include cache
fs.mkdirSync(dest, {recursive: true}); // make sure destination exists
walk(src, root); // process files, collect data and templates to render
// render templates; we do it later to make sure all data is collected first
for (const {ejs, path, data, dir, name, ext, isCollection} of templates) {
if (isCollection) {
for (const key of Object.keys(data)) {
render(ejs, path, data[key], dir, key, ext);
}
} else {
render(ejs, path, data, dir, name, ext);
}
}
function log(msg) {
if (options.log) console.log(msg);
}
function render(ejs, filename, data, dir, name, ext) {
const path = join(dir, name) + ext;
const template = compile(ejs, {
locals: Object.keys(data).concat(['root', 'rootPath']),
filename, read, resolve, cache
});
log(`render ${path}`);
fs.writeFileSync(join(dest, path), template(data));
}
function resolve(parent, filename) {
return join(dirname(parent), filename);
}
function read(filename) {
return fs.readFileSync(filename, 'utf8');
}
// create an object to be used as evalulation data in a template
function createCtx(rootPath, properties) {
// prototype magic to make sure all data objects have access to root/rootPath
// in templates and includes without them being enumerable
const ctx = Object.create(proto, {rootPath: {value: rootPath, enumerable: false}});
if (properties) Object.assign(ctx, properties);
return ctx;
}
// recursively walk through and process files inside the source directory
function walk(dir, data) {
const files = fs.readdirSync(dir);
for (const file of files) {
const path = join(dir, file);
if (relative(path, dest) === '') continue;
const shortPath = relative(src, path);
const ext = extname(path);
const name = basename(path, ext);
const rootPath = relative(dirname(shortPath), '');
const destPath = join(dest, shortPath);
if (file[0] === '.' || file === 'node_modules' || ext === '.lock' || name.endsWith('-lock')) {
log(`skip ${shortPath}`);
continue;
}
const stats = fs.lstatSync(path);
if (stats.isDirectory()) {
fs.mkdirSync(destPath, {recursive: true});
data[file] = createCtx(join(rootPath, '..'));
walk(path, data[file]);
continue;
}
if (ext === '.md') {
log(`read ${shortPath}`);
const {body, attributes} = parseFrontMatter(fs.readFileSync(path, 'utf8'));
data[name] = createCtx(rootPath, {...attributes, body: marked(body, markedOptions)});
} else if (ext === '.yml' || ext === '.yaml') {
log(`read ${shortPath}`);
data[name] = createCtx(rootPath, yaml.load(fs.readFileSync(path, 'utf8')));
} else if (ext === '.ejs') {
if (name[0] === '_') { // skip includes
log(`skip ${shortPath}`);
continue;
}
log(`compile ${shortPath}`);
templates.push({
data,
name,
path,
ejs: fs.readFileSync(path, 'utf8'),
isCollection: name === 'item',
dir: dirname(shortPath),
ext: extname(name) ? '' : '.html'
});
} else if (path !== destPath) {
log(`copy ${shortPath}`);
fs.copyFileSync(path, destPath);
}
}
}
}