美文网首页
nodejs原生模块快速熟悉

nodejs原生模块快速熟悉

作者: 我爱萝卜花 | 来源:发表于2019-05-29 15:20 被阅读0次
path
var path = require('path')
//返回一个对象,包含dirname、basename、extname等方法,如下图
console.log(path)

var filepath = '/node/base/path/test.js'
// dirname返回路径前缀
// 返回/node/base/path
console.log(
  path.dirname(filepath)
)
// basename返回路径的最后一部分,第二个参数是指定文件扩展名
// 返回 test.js test
console.log(
  path.basename(filepath),
  path.basename(filepath, '.js')
)
// extname获取文件扩展名
// 返回 .js
console.log(
  path.extname(filepath)
)
// 连接路径名
// 返回 a/b/c
console.log(
  path.join('a', 'b', 'c')
)
// 这个接口的作用就相当于在shell命令下,从左到右运行一遍cd path命令,
// 最终获取的绝对路径/文件名,就是这个接口所返回的结果了。
// 返回 / /static/img
console.log(
  path.resolve(),
  path.resolve('static/img')
)
// path.relative(from, to)
// 边界:如果from、to指向同个路径,那么返回空字符串。如果from、to中任一者为空,那么,返回当前工作路径。
// 规则先找到from, to 路径的共同父目录,apecs目录的上一级是a目录,不一样就再向上找到test目录,然后from,to都在test目录下,
// 所以是../../a/specs
// 返回
// ../../a/specs
var a = path.relative('../test/e2e/custom-assertions', '../test/a/specs')
console.log(a)
// 返回
// ''
var b = path.relative('../test/e2e/custom-assertions', '../test/e2e/custom-assertions')
console.log(b)
// 返回
// ../../..
var c = path.relative('../test/e2e/custom-assertions', '')
console.log(c)
__dirname

Node.js 中,__dirname 总是指向被执行 js 文件的绝对路径,所以当你在 /d1/d2/myscript.js 文件中写了 __dirname, 它的值就是 /d1/d2

相关文章

网友评论

      本文标题:nodejs原生模块快速熟悉

      本文链接:https://www.haomeiwen.com/subject/nerytctx.html