Node.js의 경로 처리 모듈 경로에 대한 자세한 설명

高洛峰
풀어 주다: 2016-12-28 13:51:50
원래의
1244명이 탐색했습니다.

머리말

node.js에서는 경로를 처리하고 변환하는 데 사용할 수 있는 많은 메서드와 속성이 제공됩니다. 경로 인터페이스는 용도에 따라 분류됩니다. .. 잘 생각해보면 그렇게 헷갈리지는 않을 것이다. 아래에서는 Node.js의 경로 처리 모듈 경로를 자세히 소개하겠습니다.

경로/파일 이름/확장자 가져오기

경로 가져오기: path.dirname(filepath)

파일 이름 가져오기: path.basename(filepath )

확장자 가져오기: path.extname(filepath)

경로 가져오기

예제는 다음과 같습니다.

var path = require('path');
var filepath = '/tmp/demo/js/test.js';
 
// 输出:/tmp/demo/js
console.log( path.dirname(filepath) );
로그인 후 복사

파일 이름 가져오기

엄밀히 말하면 path.basename(filepath)은 경로의 마지막 부분만 출력하고 파일 이름인지 여부는 확인하지 않습니다.

그러나 대부분의 경우 "파일 이름을 가져오는" 간단한 방법으로 사용할 수 있습니다.

var path = require('path');
 
// 输出:test.js
console.log( path.basename('/tmp/demo/js/test.js') );
 
// 输出:test
console.log( path.basename('/tmp/demo/js/test/') );
 
// 输出:test
console.log( path.basename('/tmp/demo/js/test') );
로그인 후 복사

파일 이름만 가져오고 파일 확장자는 가져오지 않으려면 어떻게 해야 하나요? 두 번째 매개변수를 사용할 수 있습니다.

// 输出:test
console.log( path.basename('/tmp/demo/js/test.js', '.js') );
로그인 후 복사

파일 확장자 가져오기

간단한 예는 다음과 같습니다.

var path = require('path');
var filepath = '/tmp/demo/js/test.js';
 
// 输出:.js
console.log( path.extname(filepath) );
로그인 후 복사
로그인 후 복사

파일 확장자 가져오기

Simple 예제는 다음과 같습니다.

var path = require('path');
var filepath = '/tmp/demo/js/test.js';
 
// 输出:.js
console.log( path.extname(filepath) );
로그인 후 복사
로그인 후 복사

보다 자세한 규칙은 다음과 같습니다. (path.basename(filepath) === B 가정)

마지막부터 차단을 시작합니다. B의 끝까지 문자입니다.

B에 .이 없거나 B의 첫 번째 문자가 .이면 빈 문자열이 반환됩니다.

path.extname('index.html')
// returns '.html'
 
path.extname('index.coffee.md')
// returns '.md'
 
path.extname('index.')
// returns '.'
 
path.extname('index')
// returns ''
 
path.extname('.index')
// returns ''
로그인 후 복사

경로 조합

path.join([...paths])
path.resolve([...paths])
로그인 후 복사

path.join([...paths])

경로를 하나로 묶은 다음 정규화합니다. 이 문장은 어차피 나로서는 이해할 수 없다. 아래 의사코드 정의를 참고하면 된다.

예는 다음과 같습니다.

var path = require('path');
 
// 输出 '/foo/bar/baz/asdf'
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
로그인 후 복사

경로 정의의 의사 코드는 다음과 같습니다.

module.exports.join = function(){
 var paths = Array.prototye.slice.call(arguments, 0);
 return this.normalize( paths.join('/') );
};
로그인 후 복사

path.resolve([...paths])

이 인터페이스에 대한 설명이 좀 깁니다. 쉘 아래에서 왼쪽에서 오른쪽으로 cd 경로 명령을 실행하고 있으며 최종적으로 얻은 절대 경로/파일 이름이 이 인터페이스에서 반환된 결과라고 상상할 수 있습니다.

예를 들어 path.resolve('/foo/bar', './baz')는 다음 명령의 결과로 볼 수 있습니다.

cd /foo/bar
cd ./baz
로그인 후 복사

더 많은 비교 예는 다음과 같습니다. 다음:

var path = require('path');
 
// 假设当前工作路径是 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path
 
// 输出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path
console.log( path.resolve('') )
 
// 输出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path
console.log( path.resolve('.') )
 
// 输出 /foo/bar/baz
console.log( path.resolve('/foo/bar', './baz') );
 
// 输出 /foo/bar/baz
console.log( path.resolve('/foo/bar', './baz/') );
 
// 输出 /tmp/file
console.log( path.resolve('/foo/bar', '/tmp/file/') );
 
// 输出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path/www/js/mod.js
console.log( path.resolve('www', 'js/upload', '../mod.js') );
로그인 후 복사

경로 구문 분석

path.parse(path)

path.normalize(filepath)

From 공식 문서 설명인 path.normalize(filepath)는 비교적 간단한 API여야 하는데, 사용할 때마다 늘 불안한 느낌이 듭니다.

왜요? API 설명이 너무 짧고 다음 내용이 포함되어 있습니다.

경로가 비어 있으면 return.(현재 작업 경로와 동일)

경로에서 반복되는 경로 구분 기호(예: Linux의 /)를 하나로 병합합니다.

경로에서 ., ..를 처리합니다. (셸의 cd와 비슷합니다..)

경로 끝에 /가 있으면 /를 유지합니다.

In other words, path.normalize is "What is the shortest path I can take that will take me to the same place as the input"
로그인 후 복사

코드 예시는 다음과 같습니다. 실제 효과를 보려면 독자가 코드를 복사하고 실행하는 것이 좋습니다.

var path = require('path');
var filepath = '/tmp/demo/js/test.js';
 
var index = 0;
 
var compare = function(desc, callback){
 console.log('[用例%d]:%s', ++index, desc);
 callback();
 console.log('\n');
};
 
compare('路径为空', function(){
 // 输出 .
 console.log( path.normalize('') );
});
 
compare('路径结尾是否带/', function(){
 // 输出 /tmp/demo/js/upload
 console.log( path.normalize('/tmp/demo/js/upload') );
 
 // /tmp/demo/js/upload/
 console.log( path.normalize('/tmp/demo/js/upload/') );
});
 
compare('重复的/', function(){
 // 输出 /tmp/demo/js
 console.log( path.normalize('/tmp/demo//js') );
});
 
compare('路径带..', function(){
 // 输出 /tmp/demo/js
 console.log( path.normalize('/tmp/demo/js/upload/..') );
});
 
compare('相对路径', function(){
 // 输出 demo/js/upload/
 console.log( path.normalize('./demo/js/upload/') );
 
 // 输出 demo/js/upload/
 console.log( path.normalize('demo/js/upload/') );
});
 
compare('不常用边界', function(){
 // 输出 ..
 console.log( path.normalize('./..') );
 
 // 输出 ..
 console.log( path.normalize('..') );
 
 // 输出 ../
 console.log( path.normalize('../') );
 
 // 输出 /
 console.log( path.normalize('/../') );
  
 // 输出 /
 console.log( path.normalize('/..') );
});
로그인 후 복사

파일 경로 분해/조합

path.format(pathObject): 특정 규칙에 따라 pathObject의 root, dir, base, name 및 ext 속성을 결합합니다. 파일 경로에.

path.parse(filepath): path.format() 메서드의 반대 작업입니다.

먼저 공식 홈페이지의 관련 속성 설명을 살펴보겠습니다.

리눅스 아래

┌─────────────────────┬────────────┐
│   dir  │ base │
├──────┬    ├──────┬─────┤
│ root │    │ name │ ext │
" / home/user/dir / file .txt "
└──────┴──────────────┴──────┴─────┘
(all spaces in the "" line should be ignored -- they are purely for formatting)
로그인 후 복사

윈도우 아래

┌─────────────────────┬────────────┐
│   dir  │ base │
├──────┬    ├──────┬─────┤
│ root │    │ name │ ext │
" C:\  path\dir \ file .txt "
└──────┴──────────────┴──────┴─────┘
(all spaces in the "" line should be ignored -- they are purely for formatting)
로그인 후 복사

path.format(pathObject)

관련 API 읽기 읽기 후 문서를 통해 나는 path.format(pathObject)에서 pathObject의 구성 속성을 더욱 간소화할 수 있다는 것을 발견했습니다.

인터페이스 설명에 따르면 다음 두 가지는 동일합니다.

루트 대 dir: 둘은 서로 교체될 수 있습니다. 차이점은 경로를 연결할 때 루트 뒤에 /가 자동으로 추가되지 않지만 dir은 자동으로 추가된다는 것입니다.

기본 vs 이름+내선: 둘은 서로 교체될 수 있습니다.

var path = require('path');
 
var p1 = path.format({
 root: '/tmp/', 
 base: 'hello.js'
});
console.log( p1 ); // 输出 /tmp/hello.js
 
var p2 = path.format({
 dir: '/tmp', 
 name: 'hello',
 ext: '.js'
});
console.log( p2 ); // 输出 /tmp/hello.js
로그인 후 복사

path.parse(filepath)

path.format(pathObject)의 역연산은 공식 홈페이지에 직접 가서 예시를 확인하세요.

네 가지 속성은 사용자에게 매우 편리하지만 path.format(pathObject)에도 네 가지 구성 속성이 있어 다소 혼동하기 쉽습니다.

path.parse('/home/user/dir/file.txt')
// returns
// {
// root : "/",
// dir : "/home/user/dir",
// base : "file.txt",
// ext : ".txt",
// name : "file"
// }
로그인 후 복사

상대 경로 가져오기

인터페이스: path.relative(from, to)

설명: from 경로에서 to 경로까지의 상대 경로입니다.

경계:

from과 to가 동일한 경로를 가리키는 경우 빈 문자열이 반환됩니다.

from 또는 to가 비어 있으면 현재 작업 경로를 반환합니다.

위의 예:

var path = require('path');
 
var p1 = path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
console.log(p1); // 输出 "../../impl/bbb"
 
var p2 = path.relative('/data/demo', '/data/demo');
console.log(p2); // 输出 ""
 
var p3 = path.relative('/data/demo', '');
console.log(p3); // 输出 "../../Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path"
로그인 후 복사

플랫폼 관련 인터페이스/속성

다음 속성과 인터페이스는 플랫폼. 즉, 동일한 속성과 인터페이스가 플랫폼에 따라 다르게 동작합니다.

path.posix: 경로 관련 속성 및 인터페이스의 Linux 구현입니다.

path.win32: 경로 관련 속성 및 인터페이스의 Win32 구현입니다.

path.sep: 경로 구분 기호입니다. 리눅스에서는 /이고, 윈도우에서는 ``입니다.

path.delimiter:path设置的分割符。linux上是:,windows上是;。

注意,当使用 path.win32 相关接口时,参数同样可以使用/做分隔符,但接口返回值的分割符只会是``。

直接来例子更直观。

> path.win32.join('/tmp', 'fuck')
'\\tmp\\fuck'
> path.win32.sep
'\\'
> path.win32.join('\tmp', 'demo')
'\\tmp\\demo'
> path.win32.join('/tmp', 'demo')
'\\tmp\\demo'
로그인 후 복사

path.delimiter

linux系统例子:

console.log(process.env.PATH)
// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
 
process.env.PATH.split(path.delimiter)
// returns ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
로그인 후 복사

windows系统例子:

console.log(process.env.PATH)
// 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'
 
process.env.PATH.split(path.delimiter)
// returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
로그인 후 복사

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用node.js能有所帮助,如果有疑问大家可以留言交流,谢谢大家对PHP中文网的支持。

更多Node.js中路径处理模块path详解相关文章请关注PHP中文网!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!