search

Home  >  Q&A  >  body text

node.js 怎么require"绝对路径"?

//文件树

/app
  ├components
  | ├login
  | |    └index.js
  | ├video
  | |    └index.js
  | └posts
  |      └index.js
  ├config
  ├containers
  | ├login
  | |    └index.js
  | ├video
  | |    └index.js
  | └posts
  |      └index.js
  └src

比如我要在containers -> login -> index.js加载components-> login -> index.js,我要这样写:

require('../../components/login');

有没有可以直接加载绝对路径的方法?类似这样:

require('/components/login');

或者其他方案?

伊谢尔伦伊谢尔伦2873 days ago707

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-17 15:33:57

    require() can use absolute paths, like this:

    var prefix = '/path/to/app';
    
    require(preifx + '/components/login');

    As mentioned above, it is not recommended to use absolute paths.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 15:33:57

    One thing you need to understand is that your node service is placed on the server. Where does the only absolute path come from (this is very similar to the front-end browser using requirejs). There is only a relative path (relative to the current server). Word).

    But you can combine __dirname and path to write a general method to get the path

    In your nodejs entry file such as app.js

    global.prefixPath = path.resolve(__dirname, 'XXX')

    When used later, you can require(global.prefixPath + 'XXX')

    https://nodejs.org/dist/lates...

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 15:33:57

    Node will have a variable and a method that can generate a path during execution:

    process.cwd() is the folder address when the node command is currently executed.
    __dirname is the address of the executed js file

    Just fight

    require('f:/code/components/login');
    require(path.resolve(process.cwd(), '../../components/login'));
    // ...

    reply
    0
  • Cancelreply