path#basename JavaScript Examples

The following examples show how to use path#basename. 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: aem-component-loader.js    From aem with MIT License 6 votes vote down vote up
export default async function aemComponentLoader(source) {
  const { context, rootContext } = this;
  const logger = this.getLogger();
  const componentData = JSON.parse(toJson(source));
  const pathBaseName = basename(context);
  const component = {
    resourceType: getResourceType(rootContext, context),
    properties: componentData[KEY_JCR_ROOT] || {},
  };

  if (!component.properties[KEY_JCR_TITLE]) {
    component.properties[KEY_JCR_TITLE] = pathBaseName;
  }

  return [
    `var component = ${JSON.stringify(component)};`,
    'module.exports = component;',
    getRequiredClientLibs(context.split(pathSeparator).join('/')),
    getRequiredHTL(logger, component, context, pathBaseName),
  ].join('\n');
}
Example #2
Source File: index.js    From SJTU-Application with MIT License 6 votes vote down vote up
async _loadFile(filePath) {
    debug('docsify')(`load > ${filePath}`)
    let content
    try {
      if (isAbsolutePath(filePath)) {
        const res = await fetch(filePath)
        if (!res.ok) {
          throw Error()
        }
        content = await res.text()
        this.lock = 0
      } else {
        content = await readFileSync(filePath, 'utf8')
        this.lock = 0
      }
      return content
    } catch (e) {
      this.lock = this.lock || 0
      if (++this.lock > 10) {
        this.lock = 0
        return
      }

      const fileName = basename(filePath)
      const result = await this._loadFile(
        resolvePathname(`../${fileName}`, filePath)
      )

      return result
    }
  }
Example #3
Source File: editor.js    From ReactSourceCodeAnalyze with MIT License 6 votes vote down vote up
function getArgumentsForLineNumber(
  editor: string,
  filePath: string,
  lineNumber: number,
): Array<string> {
  switch (basename(editor)) {
    case 'vim':
    case 'mvim':
      return [filePath, '+' + lineNumber];
    case 'atom':
    case 'Atom':
    case 'Atom Beta':
    case 'subl':
    case 'sublime':
    case 'wstorm':
    case 'appcode':
    case 'charm':
    case 'idea':
      return [filePath + ':' + lineNumber];
    case 'joe':
    case 'emacs':
    case 'emacsclient':
      return ['+' + lineNumber, filePath];
    case 'rmate':
    case 'mate':
    case 'mine':
      return ['--line', lineNumber + '', filePath];
    case 'code':
      return ['-g', filePath + ':' + lineNumber];
    default:
      // For all others, drop the lineNumber until we have
      // a mapping above, since providing the lineNumber incorrectly
      // can result in errors or confusing behavior.
      return [filePath];
  }
}
Example #4
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 #5
Source File: index.js    From fes.js with MIT License 6 votes vote down vote up
export function getLocales(cwd) {
    const files = glob
        .sync('*.js', {
            cwd
        })
        .filter(
            file => !file.endsWith('.d.ts')
                && !file.endsWith('.test.js')
                && !file.endsWith('.test.jsx')
        ).map((fileName) => {
            const locale = basename(fileName, '.js');
            return {
                locale,
                message: `require('${join(cwd, fileName)}').default`
            };
        });

    return files;
}
Example #6
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 #7
Source File: precompiler.js    From Lynx with MIT License 5 votes vote down vote up
function loadFiles(opts, callback) {
  // Build file extension pattern
  let extension = (opts.extension || 'handlebars').replace(/[\\^$*+?.():=!|{}\-[\]]/g, function(arg) { return '\\' + arg; });
  extension = new RegExp('\\.' + extension + '$');

  let ret = [],
      queue = (opts.files || []).map((template) => ({template, root: opts.root}));
  Async.whilst(() => queue.length, function(callback) {
    let {template: path, root} = queue.shift();

    fs.stat(path, function(err, stat) {
      if (err) {
        return callback(new Handlebars.Exception(`Unable to open template file "${path}"`));
      }

      if (stat.isDirectory()) {
        opts.hasDirectory = true;

        fs.readdir(path, function(err, children) {
          /* istanbul ignore next : Race condition that being too lazy to test */
          if (err) {
            return callback(err);
          }
          children.forEach(function(file) {
            let childPath = path + '/' + file;

            if (extension.test(childPath) || fs.statSync(childPath).isDirectory()) {
              queue.push({template: childPath, root: root || path});
            }
          });

          callback();
        });
      } else {
        fs.readFile(path, 'utf8', function(err, data) {
          /* istanbul ignore next : Race condition that being too lazy to test */
          if (err) {
            return callback(err);
          }

          if (opts.bom && data.indexOf('\uFEFF') === 0) {
            data = data.substring(1);
          }

          // Clean the template name
          let name = path;
          if (!root) {
            name = basename(name);
          } else if (name.indexOf(root) === 0) {
            name = name.substring(root.length + 1);
          }
          name = name.replace(extension, '');

          ret.push({
            path: path,
            name: name,
            source: data
          });

          callback();
        });
      }
    });
  },
  function(err) {
    if (err) {
      callback(err);
    } else {
      callback(undefined, ret);
    }
  });
}
Example #8
Source File: acorn.js    From PsychHelp with MIT License 5 votes vote down vote up
function help(status) {
  const print = (status == 0) ? console.log : console.error
  print("usage: " + basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6]")
  print("        [--tokenize] [--locations] [---allow-hash-bang] [--compact] [--silent] [--module] [--help] [--] [infile]")
  process.exit(status)
}
Example #9
Source File: precompiler.js    From fugu-server with Apache License 2.0 5 votes vote down vote up
function loadFiles(opts, callback) {
  // Build file extension pattern
  let extension = (opts.extension || 'handlebars').replace(/[\\^$*+?.():=!|{}\-[\]]/g, function(arg) { return '\\' + arg; });
  extension = new RegExp('\\.' + extension + '$');

  let ret = [],
      queue = (opts.files || []).map((template) => ({template, root: opts.root}));
  Async.whilst(() => queue.length, function(callback) {
    let {template: path, root} = queue.shift();

    fs.stat(path, function(err, stat) {
      if (err) {
        return callback(new Handlebars.Exception(`Unable to open template file "${path}"`));
      }

      if (stat.isDirectory()) {
        opts.hasDirectory = true;

        fs.readdir(path, function(err, children) {
          /* istanbul ignore next : Race condition that being too lazy to test */
          if (err) {
            return callback(err);
          }
          children.forEach(function(file) {
            let childPath = path + '/' + file;

            if (extension.test(childPath) || fs.statSync(childPath).isDirectory()) {
              queue.push({template: childPath, root: root || path});
            }
          });

          callback();
        });
      } else {
        fs.readFile(path, 'utf8', function(err, data) {
          /* istanbul ignore next : Race condition that being too lazy to test */
          if (err) {
            return callback(err);
          }

          if (opts.bom && data.indexOf('\uFEFF') === 0) {
            data = data.substring(1);
          }

          // Clean the template name
          let name = path;
          if (!root) {
            name = basename(name);
          } else if (name.indexOf(root) === 0) {
            name = name.substring(root.length + 1);
          }
          name = name.replace(extension, '');

          ret.push({
            path: path,
            name: name,
            source: data
          });

          callback();
        });
      }
    });
  },
  function(err) {
    if (err) {
      callback(err);
    } else {
      callback(undefined, ret);
    }
  });
}
Example #10
Source File: acorn.js    From fugu-server with Apache License 2.0 5 votes vote down vote up
function help(status) {
  const print = (status == 0) ? console.log : console.error
  print("usage: " + basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6|--ecma7]")
  print("        [--tokenize] [--locations] [---allow-hash-bang] [--compact] [--silent] [--module] [--help] [--] [infile]")
  process.exit(status)
}
Example #11
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 #12
Source File: pluginUtils.js    From fes.js with MIT License 5 votes vote down vote up
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 #13
Source File: json2dsv.js    From cs-wiki with GNU General Public License v3.0 5 votes vote down vote up
progname = basename(process.argv[1])
Example #14
Source File: dsv2json.js    From cs-wiki with GNU General Public License v3.0 5 votes vote down vote up
progname = basename(process.argv[1])
Example #15
Source File: dsv2dsv.js    From cs-wiki with GNU General Public License v3.0 5 votes vote down vote up
progname = basename(process.argv[1])
Example #16
Source File: Message.js    From ciphora with MIT License 5 votes vote down vote up
export default function Message (props) {
  let contentRender = null
  const { message, isMine, startsSequence, endsSequence, showTimestamp } = props
  const { timestamp, contentType, content } = message
  const friendlyTimestamp = moment(timestamp).calendar(null, timeFormat)

  function parseText (text) {
    // Parse links
    return text.split(SPACES_REGEX).map((part, index) =>
      LINK_REGEX.test(part) ? (
        <a href='#' key={index} onClick={() => props.onLinkClick(part)}>
          {part}
        </a>
      ) : (
        ` ${part} `
      )
    )
  }

  switch (contentType) {
    case CONTENT_TYPES.IMAGE:
      // Render as image
      const imgSrc = `file:///${content}`
      contentRender = (
        <img
          className='bubble'
          onLoad={props.onLoad}
          title={friendlyTimestamp}
          src={imgSrc}
        />
      )
      break
    case CONTENT_TYPES.FILE:
      // Render as file
      const fileName = basename(content)
      const title = `${fileName} - ${friendlyTimestamp}`
      contentRender = (
        <div
          className='bubble file'
          title={title}
          onClick={() => props.onFileClick(content)}
        >
          <i className='ion-ios-document' />
          <br />
          {fileName}
        </div>
      )
      break
    default:
      // Render as text by default
      contentRender = (
        <div className='bubble' title={friendlyTimestamp}>
          {parseText(content)}
        </div>
      )
  }

  return (
    <div
      className={classList({
        message: true,
        mine: isMine,
        start: startsSequence,
        end: endsSequence
      })}
    >
      {showTimestamp && <div className='timestamp'>{friendlyTimestamp}</div>}

      <div className='bubble-container'>{contentRender}</div>
    </div>
  )
}
Example #17
Source File: Chat.js    From ciphora with MIT License 5 votes vote down vote up
export default function Chat (props) {
  const [deleteOpacity, setDeleteOpacity] = useState(0)
  const { name, lastMessage, active } = props
  let content = null

  if (!lastMessage) {
    content = ''
  } else if (lastMessage.contentType === CONTENT_TYPES.TEXT) {
    // Text so show
    content = lastMessage.content
  } else {
    // File/image so show file name
    content = basename(lastMessage.content)
  }

  const time = lastMessage
    ? moment(lastMessage.timestamp).calendar(null, timeFormat)
    : ''
  let listItemClass = 'chat-list-item'
  if (active) {
    listItemClass += ' chat-list-item-active'
  }

  return (
    <div
      className={listItemClass}
      onClick={props.onClick}
      onMouseEnter={() => setDeleteOpacity(1)}
      onMouseLeave={() => setDeleteOpacity(0)}
    >
      {/* <img className="chat-photo" src={photo} alt="chat" /> */}
      <div className='chat-initials' alt='chat'>
        {props.id === COMPOSE_CHAT_ID ? '' : initialsise(name)}
        {props.isOnline && <div className='chat-online'></div>}
      </div>
      <div className='chat-info'>
        <div className='chat-info-left'>
          <h1 className='chat-title'>{name}</h1>
          <p className='chat-snippet'>{content}</p>
        </div>
        <div className='chat-info-right'>
          <div className='chat-time'>{time}</div>
          <div
            style={{ opacity: deleteOpacity }}
            className='chat-delete ion-md-close'
            onClick={props.onDeleteClick}
          ></div>
        </div>
      </div>
    </div>
  )
}
Example #18
Source File: js.js    From ucompress with ISC License 4 votes vote down vote up
JS = (
  source, dest, options = {},
  /* istanbul ignore next */ known = umap(new Map),
  initialSource = dirname(source),
  initialDest = dirname(dest)
) => known.get(dest) || known.set(dest, minify(source, options).then(
  ({original, code, map}) => {
    const modules = [];
    const newCode = [];
    if (options.noImport)
      newCode.push(code);
    else {
      const baseSource = dirname(source);
      const baseDest = dirname(dest);
      const re = /(["'`])(?:(?=(\\?))\2.)*?\1/g;
      let i = 0, match;
      while (match = re.exec(code)) {
        const {0: whole, 1: quote, index} = match;
        const chunk = code.slice(i, index);
        const next = index + whole.length;
        let content = whole;
        newCode.push(chunk);
        /* istanbul ignore else */
        if (
          /(?:\bfrom\b|\bimport\b\(?)\s*$/.test(chunk) &&
          (!/\(\s*$/.test(chunk) || /^\s*\)/.test(code.slice(next)))
        ) {
          const module = whole.slice(1, -1);
          if (/^[a-z@][a-z0-9/._-]+$/i.test(module)) {
            try {
              const {length} = module;
              let path = $require.resolve(module, {paths: [baseSource]});
              /* istanbul ignore next */
              if (!path.includes(module) && /(\/|\\[^ ])/.test(module)) {
                const sep = RegExp.$1[0];
                const source = module.split(sep);
                const target = path.split(sep);
                const js = source.length;
                for (let j = 0, i = target.indexOf(source[0]); i < target.length; i++) {
                  if (j < js && target[i] !== source[j++])
                    target[i] = source[j - 1];
                }
                path = target.join(sep);
                path = [
                  path.slice(0, path.lastIndexOf('node_modules')),
                  'node_modules',
                  source[0]
                ].join(sep);
              }
              else {
                let oldPath = path;
                do path = dirname(oldPath);
                while (
                  path !== oldPath &&
                  path.slice(-length) !== module &&
                  (oldPath = path)
                );
              }
              const i = path.lastIndexOf('node_modules');
              /* istanbul ignore if */
              if (i < 0)
                throw new Error('node_modules folder not found');
              const {exports: e, module: m, main, type} = $require(
                join(path, 'package.json')
              );
              /* istanbul ignore next */
              const index = (e && (e.import || e['.'].import)) || m || (type === 'module' && main);
              /* istanbul ignore if */
              if (!index)
                throw new Error('no entry file found');
              const newSource = resolve(path, index);
              const newDest = resolve(initialDest, path.slice(i), index);
              modules.push(JS(
                newSource, newDest,
                options, known,
                initialSource, initialDest
              ));
              path = uModules(
                noBackSlashes(relative(dirname(source), newSource))
              );
              /* istanbul ignore next */
              content = `${quote}${path[0] === '.' ? path : `./${path}`}${quote}`;
            }
            catch ({message}) {
              console.warn(`unable to import "${module}"`, message);
            }
          }
          /* istanbul ignore else */
          else if (!/^([a-z]+:)?\/\//i.test(module)) {
            modules.push(JS(
              resolve(baseSource, module),
              resolve(baseDest, module),
              options, known,
              initialSource, initialDest
            ));
          }
        }
        newCode.push(content);
        i = next;
      }
      newCode.push(code.slice(i));
    }
    let smCode = newCode.join('');
    if (options.sourceMap) {
      const destSource = dest.replace(/(\.m?js)$/i, `$1.source$1`);
      const json = parse(map);
      const file = basename(dest);
      json.file = file;
      json.sources = [basename(destSource)];
      smCode = smCode.replace(source, file);
      modules.push(
        saveCode(source, `${dest}.map`, stringify(json), options),
        saveCode(source, destSource, original, options)
      );
    }
    return Promise.all(
      modules.concat(saveCode(source, dest, smCode, options))
    ).then(
      () => dest,
      /* istanbul ignore next */
      err => Promise.reject(err)
    );
  }
))
Example #19
Source File: index.js    From tinyjam with ISC License 4 votes vote down vote up
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);
            }
        }
    }
}