Path related APIs

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

内容简介: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.

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

查看所有标签

猜你喜欢:

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

深入浅出WebAssembly

深入浅出WebAssembly

于航 / 电子工业出版社 / 2018-11 / 128.00元

WebAssembly是一种新的二进制格式,它可以方便地将C/C++等静态语言的代码快速地“运行”在浏览器中,这一特性为前端密集计算场景提供了无限可能。不仅如此,通过WebAssembly技术,我们还可以将基于Unity等游戏引擎开发的大型游戏快速地移植到Web端。WebAssembly技术现在已经被计划设计成W3C的标准,众多浏览器厂商已经提供了对其MVP版本标准的支持。在Google I/O ......一起来看看 《深入浅出WebAssembly》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

SHA 加密
SHA 加密

SHA 加密工具