path#dirname JavaScript Examples
The following examples show how to use
path#dirname.
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: source-map-support.js From playwright-test with MIT License | 6 votes |
// Support URLs relative to a directory, but be careful about a protocol prefix
// in case we are in the browser (i.e. directories may start with "http://" or "file:///")
function supportRelativeURL(file, url, tweak) {
if (!file) {
return url
}
const dir = dirname(file)
const match = /^\w+:\/\/[^\/]*/.exec(dir)
let protocol = match ? match[0] : ''
const startPath = dir.slice(protocol.length)
if (protocol && /^\/\w\:/.test(startPath)) {
// handle file:///C:/ paths
protocol += '/'
return (
protocol + resolve(dir.slice(protocol.length), url).replace(/\\/g, '/')
)
}
if (tweak && PW_TEST_SOURCEMAP === true) {
return resolve(PW_TEST_SOURCEMAP_PATH, url)
// return PW_TEST_SOURCEMAP_PATH + resolve(dir.slice(protocol.length), url)
}
return protocol + resolve(dir.slice(protocol.length), url)
}
Example #2
Source File: dsv2dsv.js From cs-wiki with GNU General Public License v3.0 | 6 votes |
options = program
.version(JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "../package.json"))).version)
.usage("[options] [file]")
.option("-o, --out <file>", "output file name; defaults to “-” for stdout", "-")
.option("-r, --input-delimiter <character>", "input delimiter character", defaultInDelimiter)
.option("-w, --output-delimiter <character>", "output delimiter character", defaultOutDelimiter)
.option("--input-encoding <encoding>", "input character encoding; defaults to “utf8”", "utf8")
.option("--output-encoding <encoding>", "output character encoding; defaults to “utf8”", "utf8")
.parse(process.argv)
.opts()
Example #3
Source File: serviceWithBuiltIn.js From fes.js with MIT License | 6 votes |
constructor(opts) {
process.env.FES_VERSION = require('../package').version;
process.env.FES_DIR = dirname(require.resolve('../package'));
super({
...opts,
presets: [
require.resolve('@fesjs/preset-built-in'),
...(opts.presets || [])
],
plugins: [...(opts.plugins || [])]
});
}
Example #4
Source File: cli.js From ZzFXM with MIT License | 6 votes |
options = cli({
name: 'ZzFXM Song Conversion Tool',
packageJson: resolve(dirname(fileURLToPath(import.meta.url)), 'package.json'),
inputPaths: 'single',
outputPath: 'optional',
options: [
{ name: 'ignore-errors', alias: 'i', type: Boolean, description: 'Ignore incompatability errors with ZzxFM and the source song.' },
{ name: 'no-instruments', alias: 'n', type: Boolean, description: 'Don\'t generate instrument data.'},
{ name: 'sane-instruments', alias: 's', type: Boolean, description: 'Only generate data for known instruments.'},
{ name: 'pretty-print', alias: 'p', type: Boolean, description: 'Generate human-readable output file.'},
{ name: 'format', alias: 'f', values: ['none', 'esm'], type: String, description: `Output format.`, defaultValue: 'none'},
]
})
Example #5
Source File: Generator.js From fes.js with MIT License | 6 votes |
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 #6
Source File: utils.js From rally-core-addon with Mozilla Public License 2.0 | 6 votes |
__dirname = dirname(__filename)
Example #7
Source File: xlsxTransform.js From CheatLifeRestart with MIT License | 6 votes |
async function main() {
const filePaths = process.argv.slice(2);
if(filePaths.length<0) process.exit(0);
const xlsxs = await walk(filePaths);
const sheets = {};
for(const p of xlsxs) {
const data = await read(p);
const d = dirname(p);
sheets[p] = {
dirname: d,
data
};
}
await write(
transform(sheets)
);
console.info(`
------------------------
| Transform Complete |
------------------------
`);
setTimeout(()=>{}, 1000);
}
Example #8
Source File: util.js From paypal-installments with Apache License 2.0 | 6 votes |
export function babelRequire<T>(path : string) : T {
babelRegister(dirname(path));
// $FlowFixMe
return require(path); // eslint-disable-line security/detect-non-literal-require
}
Example #9
Source File: modules.js From Kadena-Mining-Stratum with GNU General Public License v2.0 | 6 votes |
/** 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 #10
Source File: packageInfo.js From vulncost with MIT License | 6 votes |
export async function getPackageKey(pkg) {
if (pkg.version && pkg.name) {
return { name: pkg.name, version: pkg.version };
}
let dir = projectCache[pkg.fileName];
if (!dir) {
const f = finder(pkg.fileName);
dir = dirname(f.next().filename);
projectCache[pkg.fileName] = dir;
}
const name = pkg.name;
const f = finder(join(dir, 'node_modules', name));
let packageInfo = f.next().value;
// if the package doesn't start with the package name we were looking for
// then it means it's not locally installed, so let's get the version from the
// npm registry
if (!packageInfo.name || !packageInfo.name.toLowerCase().startsWith(name)) {
try {
const res = await axios.get(`https://registry.npmjs.org/${name}`);
const version = res.data['dist-tags']['latest'];
return { name, version };
} catch (err) {
return {
name,
version: 'latest',
};
}
}
return { name: packageInfo.name, version: packageInfo.version };
}
Example #11
Source File: js.js From ucompress with ISC License | 6 votes |
saveCode = (source, dest, code, options) =>
new Promise((res, rej) => {
dest = uModules(dest);
mkdir(dirname(dest), {recursive: true}, err => {
/* istanbul ignore if */
if (err)
rej(err);
else {
writeFile(dest, code, err => {
/* istanbul ignore if */
if (err)
rej(err);
else if (options.createFiles)
compress(source, dest, 'text', options)
.then(() => res(dest), rej);
else
res(dest);
});
}
});
})
Example #12
Source File: configHelpers.js From twin.macro with MIT License | 6 votes |
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 #13
Source File: path.js From bot with GNU General Public License v3.0 | 6 votes |
/**
* pathTo is a oneline solution for resolving path.resolve(__dirname, 'something.js') to an absolute path.
* I created this as a replacement for desm, because you don't need another
* npm package just for resolving this one.
* @param {ImportMeta.url} url import.meta.url
* @param {String} path
* @returns {import("fs").PathLike} Absolute path from the given path string
* @example
* // Say we call the function from src/app.js
* const envPath = pathTo('../env') // returns the full .env path outside the src dir
* const redisPath = pathTo('./utils/redis.js') // returns what you expect.
*/
export function pathTo(url, path) {
return resolve(dirname(fileURLToPath(url)), path);
}
Example #14
Source File: behavior_tree.js From aresrpg with MIT License | 6 votes |
trees = Object.fromEntries(
Object.keys(Entities).map(type => {
const tree = new DOMParser().parseFromString(
fs.readFileSync(
join(
dirname(fileURLToPath(import.meta.url)),
'behavior',
`${type}.xml`
),
'utf8'
),
'text/xml'
)
return [type, tree]
})
)
Example #15
Source File: i18n.js From i18next-fs-backend with MIT License | 5 votes |
__dirname = dirname(fileURLToPath(import.meta.url))
Example #16
Source File: world.js From aresrpg with MIT License | 5 votes |
world_folder = join(
dirname(fileURLToPath(import.meta.url)),
'..',
'world'
)
Example #17
Source File: commons.js From gidget with Apache License 2.0 | 5 votes |
export default function (metaURL = import.meta.url) {
if (typeof metaURL !== 'string') throw new Error("metaURL must be a string");
const require = createRequire(metaURL);
const __filename = fileURLToPath(metaURL);
const __dirname = dirname(__filename);
return { require, __filename, __dirname };
}
Example #18
Source File: backend.json.js From i18next-fs-backend with MIT License | 5 votes |
__dirname = dirname(fileURLToPath(import.meta.url))
Example #19
Source File: index.js From desm with MIT License | 5 votes |
function urlDirname (url) {
return dirname(fileURLToPath(url))
}
Example #20
Source File: test.js From tinyjam with ISC License | 5 votes |
fixturesDir = join(dirname(fileURLToPath(import.meta.url)), 'fixtures')
Example #21
Source File: setupTypeScript.js From rally-core-addon with Mozilla Public License 2.0 | 5 votes |
__dirname = dirname(__filename)
Example #22
Source File: file.js From flow-cadut with Apache License 2.0 | 5 votes |
writeFile = (path, data) => {
const targetDir = dirname(path);
fs.mkdirSync(targetDir, { recursive: true });
return fs.writeFileSync(path, data, { encoding: "utf8" });
}
Example #23
Source File: index.js From kit with MIT License | 5 votes |
/**
* @typedef {{
* main: string;
* site: {
* bucket: string;
* }
* }} WranglerConfig
*/
/** @type {import('.').default} */
export default function (options = {}) {
return {
name: '@sveltejs/adapter-cloudflare-workers',
async adapt(builder) {
const { main, site } = validate_config(builder);
const files = fileURLToPath(new URL('./files', import.meta.url).href);
const tmp = builder.getBuildDirectory('cloudflare-workers-tmp');
builder.rimraf(site.bucket);
builder.rimraf(dirname(main));
builder.log.info('Installing worker dependencies...');
builder.copy(`${files}/_package.json`, `${tmp}/package.json`);
// TODO would be cool if we could make this step unnecessary somehow
const stdout = execSync('npm install', { cwd: tmp });
builder.log.info(stdout.toString());
builder.log.minor('Generating worker...');
const relativePath = posix.relative(tmp, builder.getServerDirectory());
builder.copy(`${files}/entry.js`, `${tmp}/entry.js`, {
replace: {
SERVER: `${relativePath}/index.js`,
MANIFEST: './manifest.js'
}
});
writeFileSync(
`${tmp}/manifest.js`,
`export const manifest = ${builder.generateManifest({
relativePath
})};\n\nexport const prerendered = new Map(${JSON.stringify(
Array.from(builder.prerendered.pages.entries())
)});\n`
);
await esbuild.build({
platform: 'browser',
sourcemap: 'linked',
target: 'es2020',
...options,
entryPoints: [`${tmp}/entry.js`],
outfile: main,
bundle: true,
external: ['__STATIC_CONTENT_MANIFEST', ...(options?.external || [])],
format: 'esm'
});
builder.log.minor('Copying assets...');
builder.writeClient(site.bucket);
builder.writeStatic(site.bucket);
builder.writePrerendered(site.bucket);
}
};
}
Example #24
Source File: laodeai.test.js From bot with GNU General Public License v3.0 | 5 votes |
readFile = (path) =>
readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), path), {
encoding: "utf-8"
})
Example #25
Source File: server.js From asymptoteWebApplication with GNU Lesser General Public License v3.0 | 5 votes |
__dirname = dirname(__filename)
Example #26
Source File: isUnsafeCallee.spec.js From js-x-ray with MIT License | 5 votes |
__dirname = dirname(fileURLToPath(import.meta.url))
Example #27
Source File: constants.js From BlockYouTubeAdsShortcut with GNU General Public License v3.0 | 5 votes |
__dirname = dirname(fileURLToPath(import.meta.url))
Example #28
Source File: index.js From HinataMd with GNU General Public License v3.0 | 5 votes |
__dirname = dirname(fileURLToPath(import.meta.url))
Example #29
Source File: genChangelog.js From GooseMod with MIT License | 5 votes |
__dirname = dirname(fileURLToPath(import.meta.url))