Giter Site home page Giter Site logo

path-browserify's Introduction

path-browserify Build Status

The path module from Node.js for browsers

This implements the Node.js path module for environments that do not have it, like browsers.

path-browserify currently matches the Node.js 10.3 API.

Install

You usually do not have to install path-browserify yourself! If your code runs in Node.js, path is built in. If your code runs in the browser, bundlers like browserify or webpack include the path-browserify module by default.

But if none of those apply, with npm do:

npm install path-browserify

Usage

var path = require('path')

var filename = 'logo.png';
var logo = path.join('./assets/img', filename);
document.querySelector('#logo').src = logo;

API

See the Node.js path docs. path-browserify currently matches the Node.js 10.3 API. path-browserify only implements the POSIX functions, not the win32 ones.

Contributing

PRs are very welcome! The main way to contribute to path-browserify is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js. This module intends to provide exactly the same API as Node.js, so features that are not available in the core path module will not be accepted. Feature requests should instead be directed at nodejs/node and will be added to this module once they are implemented in Node.js.

If there is a difference in behaviour between Node.js's path module and this module, please open an issue!

License

MIT

path-browserify's People

Contributors

chalker avatar goto-bus-stop avatar kenjibito avatar zo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

path-browserify's Issues

require('path-browserify')

hmmm, the README says to write: var path = require('path')

that didn't work for me, however it did work when i wrote: var path = require('path-browserify')

i highly doubt the README is wrong given how many people use this package, scratching my head here a bit...

Error in browser: `process` is not defined

When calling `path.resolve("tmp", ".."), this branch is triggered, causing an error in the browser (line 124 in index.js):

if (cwd === undefined)
  cwd = process.cwd();
path = cwd;
Uncaught ReferenceError: process is not defined

I think this error should be caught.

How to use this library from CDN?

I've tried to use on Codepen: https://cdn.jsdelivr.net/npm/path-browserify but this library can't be used in browser because it use module.export not UMD.

So I've tried to use browserify to build standalone file but it doesn't work:

browserify -s path -o path.js -e node_modules/path-browserify/index.js

got error that path.join is not a function because path is empty object.

How anyone can use this library in browser?

TypeError: process.cwd is not a function

vue3 + vite

import { resolve } from 'path-browserify'
resolve(basePath, childpath)
index.js:124  Uncaught (in promise) TypeError: process.cwd is not a function
    at resolve (index.js:124:25)
   ......

Windows support

The separator is hard-coded as '/' but in reality, node also supports windows which has '' as default separator (see http://nodejs.org/api/path.html#path_path_sep ). This should be automatically detected and all fns that split things up depending upon the separator should should the os-proper separator.

Use deno_std path module?

Would you mind switch to use deno_std's path module? API is compatible with Node.js, simply use deno bundle to output es module, make bundlers do tree shaking better

// mod.ts
import { win32, posix } from 'https://deno.land/[email protected]/path/mod.ts'

export { win32, posix }

export const {
  basename,
  delimiter,
  dirname,
  extname,
  format,
  fromFileUrl,
  isAbsolute,
  join,
  normalize,
  parse,
  relative,
  resolve,
  sep,
  toFileUrl,
  toNamespacedPath
} = posix
deno bundle mod.ts index.js
// package.json
{
  "module": "./index.js",
  "main": "./index.js",
  "type": "module"
}

[email protected]+element-plus@^2.3.12+path-browserify@^1.0.1 使用报错解决办法

基础环境

[email protected]
element-plus@^2.3.12
path-browserify@^1.0.1

vite 移除了node的垫片包, 所以 , 所以,在使用 path-browserify 一定会报错, process is not defined

解决办法

源码中, 作者没有去处理这个问题,那么, 我们将源码中的 resolve方法 copy到项目中即可

说白了 你就是要解决 path.resolve(‘/a’, 'b') --> /a/b 这个问题

第一步

复制 normalizeStringPosix 方法 和 resolve 方法 到你项目的utils 里面,作为一个工具包

function normalizeStringPosix(path, allowAboveRoot) {
  var res = '';
  var lastSegmentLength = 0;
  var lastSlash = -1;
  var dots = 0;
  var code;
  for (var i = 0; i <= path.length; ++i) {
    if (i < path.length)
      code = path.charCodeAt(i);
    else if (code === 47 /*/*/)
      break;
    else
      code = 47 /*/*/;
    if (code === 47 /*/*/) {
      if (lastSlash === i - 1 || dots === 1) {
        // NOOP
      } else if (lastSlash !== i - 1 && dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {
          if (res.length > 2) {
            var lastSlashIndex = res.lastIndexOf('/');
            if (lastSlashIndex !== res.length - 1) {
              if (lastSlashIndex === -1) {
                res = '';
                lastSegmentLength = 0;
              } else {
                res = res.slice(0, lastSlashIndex);
                lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
              }
              lastSlash = i;
              dots = 0;
              continue;
            }
          } else if (res.length === 2 || res.length === 1) {
            res = '';
            lastSegmentLength = 0;
            lastSlash = i;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          if (res.length > 0)
            res += '/..';
          else
            res = '..';
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0)
          res += '/' + path.slice(lastSlash + 1, i);
        else
          res = path.slice(lastSlash + 1, i);
        lastSegmentLength = i - lastSlash - 1;
      }
      lastSlash = i;
      dots = 0;
    } else if (code === 46 /*.*/ && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}

/**
 * link 代码来源 [email protected]
 * @returns
 */
export function resolve() {
  var resolvedPath = '';
  var resolvedAbsolute = false;
  var cwd;

  for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    var path;
    if (i >= 0)
      path = arguments[i];
    else {
      if (cwd === undefined)
        // cwd = process.cwd();
      path = '';
    }

    // Skip empty entries
    if (path.length === 0) {
      continue;
    }

    resolvedPath = path + '/' + resolvedPath;
    resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;
  }

  // At this point the path should be resolved to a full absolute path, but
  // handle relative paths to be safe (might happen when process.cwd() fails)

  // Normalize the path
  resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);

  if (resolvedAbsolute) {
    if (resolvedPath.length > 0)
      return '/' + resolvedPath;
    else
      return '/';
  } else if (resolvedPath.length > 0) {
    return resolvedPath;
  } else {
    return '.';
  }
}

第二步: 注释有关 process相关的,其实就一行, 然后将 path = ''

使用

<script setup name="SidebarItem">
import { isExternal, resolve} from '@/utils/index.js'

const resolvePath = routePath => {
  if (isExternal(routePath)) {
    return routePath
  }

  if (isExternal(props.basePath)) {
    return props.basePath
  }

  const fullPath = resolve(props.basePath, routePath)

  console.log(fullPath);

  return fullPath
}
</script>

我看有评论说 , 在vite.config.js 给全局注入一个process 空对象,其实这里会执行 process.cwd() , 空对象.cwd() 执行方法也会报错,除非提供完整的, 这个其实麻烦了一些。 可能还有直接引入 Node的 pollyfill 包, 也不是很好

使用demo

console.log(`示例:resolve('/a', 'b'), 结果:`,resolve('/a', 'b'));  

console.log(`示例:resolve('/a', 'b', 'c')  结果:`,resolve('/a', 'b', 'c'));  

console.log(`示例:resolve('/a', '/b')  结果:`, resolve('/a', '/b')); 
console.log(`示例:resolve('a', 'b')  结果:`,resolve('a', 'b'));

输出:

示例:resolve('/a', 'b') 结果: /a/b
示例:resolve('/a', 'b', 'c')  结果: /a/b/c
示例:resolve('/a', '/b')  结果: /b
示例:resolve('a', 'b')  结果: a/b

解决问题不易: 如果可以, 掘金给我一个小小的 star 掘金地址 ,谢谢

please change

please change this

exports.isAbsolute = function(path) {
        return path.charAt(0) === '/';
  };

to

exports.isAbsolute = function(path) {
        return path && path.charAt(0) === '/';
  };

simple one

thank you substack

Error in Webpack 5

Looks like require.resolve doesnt work anymore in Webpack 5?

ERROR in ./src/renderer/services/Config.ts 26:26-41
Module not found: Error: Can't resolve 'path' in '/Users/chet/Code/brain-web/object-system/src/renderer/services'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
	- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
	- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
	resolve.fallback: { "path": false }
 @ ./src/renderer/renderer.tsx 26:17-45

path.join universal front - backslash not implemented

Node's version of path.join converts the front or backslash appropriately depending on the operating system. For example, windows uses a frontslash for its directories. And linux and mac use a backslash for their directories.

The issue is when coding on Windows, you must use a frontslash. But when deploying on Mac, it must be converted to a backslash. This presents a portability issue.

Node's "join" actually handles this quite simply using conditionals to determine which operating system the user is on. But this version does not handle the front/backslash problem. Is it possible to implement Node's version of "join" in this module?

Update to use newer node path code

The version of path this uses is very old - many things won't work, eg my code uses path.posix because it needs to process posix paths even when running on windows, but it's missing in this version so you get undefined error in browser. Also path.parse and etc

I'd be happy to do a PR but only if it's welcome and likely to actually get merged - hasn't been any activity here in four years

Alternately is there a way to override core things like path in browserify? I read the manual etc but couldn't find anything. May have missed it.

Won’t work in browser because of process.cwd()?

Admittedly I’m not using this through Browserify so not sure if that would make a difference, but this lib calls process.cwd() which isn’t available in browsers (process isn’t at all).

I wonder if it could be adapted to not use this — or at least use a default / accept a config option (empty string?) when process.cwd() isn’t available — and hence be more portable.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.