简体   繁体   中英

Path.join cross platform in Nodejs for require

I remember long time ago in Node js, it was needed to use path.join in order to load local modules cross-platform. I simply want to know still do we need such strategy or it is not needed anymore for Node 12+?

Thanks

Eg

const i= require(path.join(__dirname,'config','myModule'))

instead of writing

const i=require('./config/module')

Either will work just fine and have been just fine in node.js for as long as I can remember. The module loading rules for require() are fully documented here . Your specific case should be covered by the very first section and step 3a which is this:

require(X) from module at path Y
1. If X is a core module,
   a. return the core module
   b. STOP
2. If X begins with '/'
   a. set Y to be the filesystem root
3. If X begins with './' or '/' or '../'
   a. LOAD_AS_FILE(Y + X)

The times when you may need to use path.join() are when you may be constructing a path that you will send to some external module that requires OS-specific path separators or when you just want path.join() to handle making sure there is one and only one path separator between pieces you are joining (like when you don't know if individual pieces already have leading or trailing slashes).

require() itself will work fine with / as a path separator on any supported platform so require('./config/module') will be fine on Windows even though the OS path separator is \\ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM