Path related APIs

栏目: IT技术 · 发布时间: 5年前

内容简介:switch current working directory intoThe process.cwd() method returns the current working directory of the node.js process. i.e. the directory from which you invoked the
+-- myProject
|	+-- node_modules
|		+-- lodash
|	+-- src
|   	+-- cwd.js
|		+-- dirname.js
|		+-- require.js

switch current working directory into myProject

pwd // '/Users/michaelzheng/Desktop/myProject'

process.cwd

The process.cwd() method returns the current working directory of the node.js process. i.e. the directory from which you invoked the node command.

relative to the process

#!/usr/bin/env node

// cwd.js
process.cwd(); 
// Returns '/Users/michaelzheng/Desktop/myProject'

Use case: fetch project config file which is usually set based on project root. e.g. webpack config file.

__dirname

returns the directory name of the directory containing the JavaScript source code file.

relative to the source code

#!/usr/bin/env node

// dirname.js
__dirname; 
// Returns '/Users/michaelzheng/Desktop/myProject/src'

Use case: get absolute path of a file

require.resolve

use(es) the internal require() machinery to look up the location of a module, but rather than loading the module, just return(s) the resolved filename.

works for module resolution

// require.js
require.resolve('lodash'); 
// Returns /Users/michaelzheng/Desktop/myProject/node_modules/lodash/lodash.js

Use case: resolve node modules which are not installed on current working directory.

path.resolve

The path.resolve() method resolves a sequence of paths or path segments into an absolute path .

always returns absolute path

path.resolve('/foo/bar', './baz');
// Returns: '/foo/bar/baz'

path.resolve('/foo/bar', '/tmp/file/');
// Returns: '/tmp/file'

path.join

The path.join() method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); 
// Returns '/foo/bar/baz/asdf'

path.join('foo', 'bar', 'baz/asdf', 'quux', '..'); 
// Returns 'foo/bar/baz/asdf'

Notice

  • If you want to follow the latest news/articles for the series of my blogs, Please 「Watch」 to Subscribe.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

代码整洁之道:程序员的职业素养

代码整洁之道:程序员的职业素养

罗伯特·C.马丁 (Robert C.Martin) / 余晟、章显洲 / 人民邮电出版社 / 2016-9-1 / 49.00元

1. 汇聚编程大师40余年编程生涯的心得体会 2. 阐释软件工艺中的原理、技术、工具和实践 3. 助力专业软件开发人员具备令人敬佩的职业素养 成功的程序员在以往的工作和生活中都曾经历过大大小小的不确定性,承受过永无休止的压力。他们之所以能够成功,是因为拥有一个共同点,都深切关注创建软件所需的各项实践。他们将软件开发视为一种需要精雕细琢加以修炼的技艺,他们以专业人士的标准要求自己,......一起来看看 《代码整洁之道:程序员的职业素养》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

html转js在线工具
html转js在线工具

html转js在线工具