path#join JavaScript Examples

The following examples show how to use path#join. 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: wubbfont.js    From gidget with Apache License 2.0 6 votes vote down vote up
async run(bot, message, args) {
    if (!args[1]) return message.channel.send("Put something");
    const text = args.slice(1).join(" ")
    message.channel.sendTyping();
    const canvas = Canvas.createCanvas(WIDTH, HEIGHT);
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = '#2E3192';
    const ctxt = new canvasTxt({ font: 'hhs', fontSize: 130, fontStyle: '#2E3192' })
    ctx.shadowBlur = 3;
    ctx.shadowColor = "white";
    const { height } = ctxt.drawText(ctx, text, 0, 0, WIDTH, HEIGHT, false);
    if (height > 665) return message.channel.send("There is a limit of 7 lines. Your text exceeded that limit");
    ctx.strokeStyle = "white";
    ctxt.drawText(ctx, text, 0, 0, WIDTH, HEIGHT, true);
    const att = new MessageAttachment(canvas.toBuffer(), "wubbtext.png");
    await message.channel.send({ files: [att] });
  }
Example #2
Source File: converter.js    From HinataMd with GNU General Public License v3.0 6 votes vote down vote up
function ffmpeg(buffer, args = [], ext = '', ext2 = '') {
  return new Promise(async (resolve, reject) => {
    try {
      let tmp = join(global.__dirname(import.meta.url), '../tmp', + new Date + '.' + ext)
      let out = tmp + '.' + ext2
      await promises.writeFile(tmp, buffer)
      spawn('ffmpeg', [
        '-y',
        '-i', tmp,
        ...args,
        out
      ])
        .on('error', reject)
        .on('close', async (code) => {
          try {
            await promises.unlink(tmp)
            if (code !== 0) return reject(code)
            resolve({
              data: await promises.readFile(out),
              filename: out,
              delete() {
                return promises.unlink(out)
              }
            })
          } catch (e) {
            reject(e)
          }
        })
    } catch (e) {
      reject(e)
    }
  })
}
Example #3
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 #4
Source File: api.js    From nextjs-101 with MIT License 6 votes vote down vote up
export function getPostBySlug(slug, fields = []) {
  const realSlug = slug.replace(/\.md$/, "");
  const fullPath = join(postsDirectory, `${realSlug}.md`);
  const fileContents = fs.readFileSync(fullPath, "utf8");
  const { data, content } = matter(fileContents);

  const items = {};

  // Ensure only the minimal needed data is exposed
  fields.forEach((field) => {
    if (field === "slug") {
      items[field] = realSlug;
    }
    if (field === "content") {
      items[field] = content;
    }

    if (data[field]) {
      items[field] = data[field];
    }
  });
  return items;
}
Example #5
Source File: update-user.service.js    From saasgear with MIT License 6 votes vote down vote up
export async function changeUserAvatar(fileData, user) {
  try {
    const file = await fileData;
    const fileName = `avatar-${user.id}-new-${new Date().getTime()}-${file.filename}`;
    const stream = file.createReadStream();
    await new Promise((resolve, reject) => {
      const writeStream = createWriteStream(join(FOLDER_PATHS.avatarDir, fileName));
      writeStream.on('finish', () => resolve());
      writeStream.on('error', async (error) => reject(error));
      stream.on('error', (error) => writeStream.destroy(error));
      stream.pipe(writeStream);
    });
    await updateUser(user.id, { avatar_url: fileName });
    return { url: fileName };
  } catch (error) {
    logger.error(error);
    throw new ApolloError('Something went wrong!');
  }
}
Example #6
Source File: xlsxTransform.js    From CheatLifeRestart with MIT License 6 votes vote down vote up
async function write(sheets) {
    for(const sheetName in sheets) {
        const { dirname, data, source } = sheets[sheetName];
        const savePath = join(dirname, `${sheetName}.json`);
        console.info('[Transform] XLSX(', source.map(([p, s])=>`${p}:${s}`).join('\n\t\t  '), `) \n\t -> JSON( ${savePath} )`);
        await writeFile(
            savePath,
            JSON.stringify(data, null, 4),
        )
    }
}
Example #7
Source File: obfuscated.spec.js    From js-x-ray with MIT License 6 votes vote down vote up
test("should detect 'jsfuck' obfuscation", (tape) => {
  const trycatch = readFileSync(join(FIXTURE_PATH, "jsfuck.js"), "utf-8");
  const { warnings } = runASTAnalysis(trycatch);

  tape.strictEqual(warnings.length, 1);
  tape.deepEqual(getWarningKind(warnings), ["obfuscated-code"].sort());
  tape.strictEqual(warnings[0].value, "jsfuck");
  tape.end();
});
Example #8
Source File: next.js    From flatris-LAB_V1 with MIT License 6 votes vote down vote up
export async function startNextApp(
  app: express$Application,
  server: net$Server
) {
  const dev = process.env.NODE_ENV !== 'production';
  const nextApp = next({ dev, dir: join(__dirname, '../web') });
  const nextHandler = nextApp.getRequestHandler();

  await nextApp.prepare();

  app.get('/favicon.ico', (req: express$Request, res: express$Response) => {
    const path = join(__dirname, '../static/favicon.ico');
    return nextApp.serveStatic(req, res, path);
  });

  app.get('/join/:id', (req: express$Request, res: express$Response) => {
    const params = { g: req.params.id };
    return nextApp.render(req, res, '/join', params);
  });

  app.get('*', (req: express$Request, res: express$Response) => {
    return nextHandler(req, res);
  });
  var port = process.env.PORT || 3000;
  startServer(server, port);
}
Example #9
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 #10
Source File: index.js    From ucompress with ISC License 6 votes vote down vote up
crawl = (source, options) => new Promise((res, rej) => {
  stat(source, (err, stat) => {
    /* istanbul ignore if */
    if (err)
      rej(err);
    else {
      if (stat.isFile())
        copy(source, source, options).then(res, rej);
      /* istanbul ignore else */
      else if (stat.isDirectory())
        readdir(source, (err, files) => {
          /* istanbul ignore if */
          if (err)
            rej(err);
          else
            Promise.all(files
              .filter(file => !/^[._]/.test(file))
              .map(file => crawl(join(source, file), options))
            ).then(res, rej);
        });
    }
  });
})
Example #11
Source File: behavior_tree.js    From aresrpg with MIT License 6 votes vote down vote up
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 #12
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 #13
Source File: AlphaFilter.js    From inkpaint with MIT License 6 votes vote down vote up
constructor(alpha = 1.0) {
    super(
      // vertex shader
      readFileSync(join(__dirname, "../fragments/default.vert"), "utf8"),
      // fragment shader
      readFileSync(join(__dirname, "./alpha.frag"), "utf8")
    );

    this.alpha = alpha;
    this.glShaderKey = "alpha";
  }
Example #14
Source File: api.js    From next-tina-blog-starter with MIT License 6 votes vote down vote up
export function getPostBySlug(slug, fields = []) {
  const realSlug = slug.replace(/\.md$/, '')
  const fullPath = join(postsDirectory, `${realSlug}.md`)
  const fileContents = fs.readFileSync(fullPath, 'utf8')
  const { data, content } = matter(fileContents)

  const items = {}

  // Ensure only the minimal needed data is exposed
  fields.forEach(field => {
    if (field === 'slug') {
      items[field] = realSlug
    }
    if (field === 'content') {
      items[field] = content
    }

    if (data[field]) {
      items[field] = data[field]
    }
  })

  return items
}
Example #15
Source File: prepareModules.js    From vuems with Open Software License 3.0 6 votes vote down vote up
/**
 * Set plugins for modules
 * @function setPlugins
 * @param {Object[]} configurations - All modules configurations
 * @param {Object} options - Module options
 * @param {string} options.allModules - All active modules
 * @returns {Promise<string>}
 */
async function setPlugins(configurations, { allModules }) {
    await Promise.all(
        configurations
            .filter((configuration) => configuration.plugins)
            .map(({ name, plugins }) => {
                const moduleName = name.replace(/[^a-zA-Z]/g, '');

                return plugins.map(({ ssr, src }) => {
                    const pluginPath = join(
                        allModules.find((m) => m.name === name).path,
                        src,
                    ).replace(/\/$/g, '');

                    return this.addPlugin({
                        src: `${pluginPath}.js`,
                        fileName: join('modules', moduleName, `${src}.js`),
                        options: {
                            mode: ssr ? 'server' : 'client',
                        },
                    });
                });
            }),
    );

    return 'All plugins set';
}
Example #16
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 #17
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 #18
Source File: index.js    From watchlist with MIT License 6 votes vote down vote up
// modified: lukeed/totalist
async function walk(dir, callback, pre='') {
	await toRead(dir).then(arr => {
		return Promise.all(
			arr.map(str => {
				let abs = join(dir, str);
				return toStats(abs).then(stats => {
					if (!stats.isDirectory()) return;
					callback(join(pre, str), abs, stats);
					return walk(abs, callback, join(pre, str));
				});
			})
		);
	});
}
Example #19
Source File: telemeter.js    From medusa with MIT License 6 votes vote down vote up
getCliVersion() {
    try {
      const jsonfile = join(
        require
          .resolve(`@medusajs/medusa-cli`) // Resolve where current gatsby-cli would be loaded from.
          .split(sep)
          .slice(0, -2) // drop lib/index.js
          .join(sep),
        `package.json`
      )

      const { version } = require(jsonfile)
      return version
    } catch (e) {
      if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
        console.error("failed to get medusa version", e)
      }
    }

    return `-0.0.0`
  }
Example #20
Source File: file_mgr.js    From freyr-js with Apache License 2.0 6 votes vote down vote up
export default async function genFile(opts) {
  opts = opts || {};
  if (opts.filename) {
    opts.tmpdir = opts.tmpdir || tmpdir();
    if (!(await exists(opts.tmpdir))) throw new Error('tmpdir does not exist');
    const dir = join(opts.tmpdir, opts.dirname || '.');
    await mkdirp(dir);
    const name = join(dir, opts.filename);
    const fd = await open(name, fs.constants.O_CREAT);
    hookupListeners();
    let closed = false;
    const garbageHandler = () => {
      if (closed) return;
      fs.closeSync(fd);
      closed = true;
      if (!opts.keep) fs.unlinkSync(name);
    };
    removeCallbacks.unshift(garbageHandler);
    return {
      fd,
      name,
      removeCallback: async () => {
        if (closed) return;
        await close(fd);
        closed = true;
        await unlink(name);
        removeCallbacks.splice(removeCallbacks.indexOf(garbageHandler), 1);
      },
    };
  }
  return new Promise((res, rej) =>
    tmp.file(opts, (err, name, fd, removeCallback) => (err ? rej(err) : res({fd, name, removeCallback}))),
  );
}
Example #21
Source File: test.js    From tinyjam with ISC License 6 votes vote down vote up
function testDir(t, input, expected) {
    const inputPath = join(fixturesDir, input);
    const expectedPath = join(fixturesDir, expected);
    const actualPath = `${expectedPath}_actual`;

    rimraf.sync(actualPath);

    tinyjam(inputPath, actualPath);

    const result = dircompare.compareSync(actualPath, expectedPath, {compareContent: true});
    if (result.same) {
        t.pass('folders equal');
        rimraf.sync(actualPath);
    } else {
        console.error(result.diffSet.filter(r => r.reason));
        t.fail('folders different');
    }

    t.end();
}
Example #22
Source File: packageInfo.js    From vulncost with MIT License 6 votes vote down vote up
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 #23
Source File: index.spec.js    From kit with MIT License 6 votes vote down vote up
test('load default config (esm)', async () => {
	const cwd = join(__dirname, 'fixtures/default');

	const config = await load_config({ cwd });
	remove_keys(config, ([, v]) => typeof v === 'function');

	const defaults = get_defaults(cwd + '/');
	defaults.kit.version.name = config.kit.version.name;

	assert.equal(config, defaults);
});
Example #24
Source File: Plugin.js    From the-eye-knows-the-garbage with MIT License 6 votes vote down vote up
importMethod(methodName, file, pluginState) {
    if (!pluginState.selectedMethods[methodName]) {
      const libraryDirectory = this.libraryDirectory;
      const style = this.style;
      const transformedMethodName = this.camel2UnderlineComponentName  // eslint-disable-line
        ? transCamel(methodName, '_')
        : this.camel2DashComponentName
          ? transCamel(methodName, '-')
          : methodName;
      const path = winPath(
        this.customName ? this.customName(transformedMethodName) : join(this.libraryName, libraryDirectory, transformedMethodName, this.fileName) // eslint-disable-line
      );
      pluginState.selectedMethods[methodName] = this.transformToDefaultImport  // eslint-disable-line
        ? addDefault(file.path, path, { nameHint: methodName })
        : addNamed(file.path, methodName, path);
      if (this.customStyleName) {
        const stylePath = winPath(this.customStyleName(transformedMethodName));
        addSideEffect(file.path, `${stylePath}`);
      } else if (this.styleLibraryDirectory) {
        const stylePath = winPath(
          join(this.libraryName, this.styleLibraryDirectory, transformedMethodName, this.fileName)
        );
        addSideEffect(file.path, `${stylePath}`);
      } else if (style === true) {
        addSideEffect(file.path, `${path}/style`);
      } else if (style === 'css') {
        addSideEffect(file.path, `${path}/style/css`);
      } else if (typeof style === 'function') {
        const stylePath = style(path, file);
        if (stylePath) {
          addSideEffect(file.path, stylePath);
        }
      }
    }
    return Object.assign({}, pluginState.selectedMethods[methodName]);
  }
Example #25
Source File: livecapture.js    From gidget with Apache License 2.0 5 votes vote down vote up
async run(bot, interaction) {
    //Check valid URL
    const check = isURL(interaction.options.getString("video", true));
    if (!check) return await interaction.reply("Invalid URL!");
    //Cooldown
    if (interaction.user.id !== "577000793094488085") {
      if (!timer.has(interaction.user.id)) {
        timer.add(interaction.user.id);
        setTimeout(() => {
          timer.delete(interaction.user.id);
        }, 60000);
      } else {
        return await interaction.reply({ content: "Don't overload this command! (1 min cooldown)", ephemeral: true });
      }
    }
    try {
      //Some random name for the temp file
      const name = crypto.randomBytes(20).toString('hex');
      //Paths
      const pathTS = join(__dirname, '../../tmp', `/${name}.ts`);
      const pathPNG = join(__dirname, '../../tmp', `/${name}.png`);
      await interaction.deferReply();
      //Create a TS file
      const stl = execaCommand(`streamlink -o ${pathTS} ${interaction.options.getString("video", true)} best`, { reject: false })
      stl.then(async (a) => {
        if(a.stdout.includes("error")) return await interaction.editReply("Link isn't a live stream, stream not available, or incompatible stream.");
        await execa(ffmpeg, ['-i', pathTS, '-vframes', '1', pathPNG])
          //All correct.
          .then(async () => {
            //Read file
            const buf = await fs.promises.readFile(pathPNG);
            //Send to Discord
            const att = new MessageAttachment(buf, "image.png");
            await interaction.editReply({ files: [att] });
          })
          //Any errors here
          .catch(err => interaction.editReply(`Some error ocurred. Here's a debug: ${err}`))
      }).then(() => {
        fs.promises.unlink(pathTS).catch(()=>{});
        fs.promises.unlink(pathPNG).catch(()=>{});
      });
      setTimeout(() => {
        if(!stl.killed) stl.kill();
      }, 3500);
    } catch (err) {
      //Errors
      if (interaction.replied || interaction.deferred) interaction.editReply(err.toString());
      else interaction.reply(err.toString());
    }
  }
Example #26
Source File: index.js    From HinataMd with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Start a js file
 * @param {String} file `path/to/file`
 */
function start(file) {
  if (isRunning) return
  isRunning = true
  let args = [join(__dirname, file), ...process.argv.slice(2)]
  say([process.argv[0], ...args].join(' '), {
    font: 'console',
    align: 'center',
    gradient: ['red', 'magenta']
  })
  setupMaster({
    exec: args[0],
    args: args.slice(1),
  })
  let p = fork()
  p.on('message', data => {
    console.log('[RECEIVED]', data)
    switch (data) {
      case 'reset':
        p.process.kill()
        isRunning = false
        start.apply(this, arguments)
        break
      case 'uptime':
        p.send(process.uptime())
        break
    }
  })
  p.on('exit', (_, code) => {
    isRunning = false
    console.error('Exited with code:', code)
    if (code === 0) return
    watchFile(args[0], () => {
      unwatchFile(args[0])
      start(file)
    })
  })
  let opts = new Object(yargs(process.argv.slice(2)).exitProcess(false).parse())
  if (!opts['test'])
    if (!rl.listenerCount()) rl.on('line', line => {
      p.emit('message', line.trim())
    })
  // console.log(p)
}
Example #27
Source File: i18n.js    From GooseMod with MIT License 5 votes vote down vote up
distDir = resolve(join(__dirname, '..', '..', 'dist'))