>  기사  >  웹 프론트엔드  >  노드의 경로 모듈에 대한 간략한 분석

노드의 경로 모듈에 대한 간략한 분석

青灯夜游
青灯夜游앞으로
2023-02-17 14:35:302407검색

경로 모듈은 파일/디렉토리 경로를 처리하기 위해 nodejs에 내장된 모듈로, 경로 처리와 관련된 다양한 방법을 제공하는 도구 상자로 간주할 수 있습니다. 동시에 웹팩을 구성할 때와 같은 프런트엔드 개발에서 경로 모듈이 자주 등장합니다. 이번 글에서는 node의 path 모듈에 대해 이야기하겠습니다.

노드의 경로 모듈에 대한 간략한 분석

노드의 경로 모듈

머리말: 이 글을 통해 노드의 경로 내장 모듈의 일부 API에 대해 배우게 됩니다
필요한 경우 노드 공식 웹사이트에서 확인할 수 있습니다. 물론 이론보다 실천이 중요
그래서 실천을 위한 사례를 준비했습니다

1 경로 모듈에 대한 첫 번째 소개

경로 모듈은 경로 처리를 위해 Node.js에서 공식적으로 제공하는 모듈입니다. . 경로 처리에 대한 사용자의 요구 사항을 충족하기 위해 일련의 메서드와 속성을 제공합니다.

2.path 모듈 API

2.1 path.join()

path.join() 메서드, 여러 경로 조각을 전체 경로 문자열로 연결하는 데 사용됨

구문 형식 is
노드의 경로 모듈에 대한 간략한 분석

...paths(string) 경로 조각의 시퀀스는 연결해야 하는 모든 경로의 시리즈입니다. [관련 튜토리얼 권장 사항 : nodejs 비디오 자습서, 프로그램 교육 ]

값은 String노드의 경로 모듈에 대한 간략한 분석

//引入path模块
const path=require("path")
//书写要拼接的路径
const pathStr=path.join('/a','/b/c','../','./d','e')

console.log(pathStr)

2.2 path.basename ()

임을 지적해야합니다. path.basename() 메소드를 사용하면 경로의 마지막 부분을 가져올 수 있습니다.


노드의 경로 모듈에 대한 간략한 분석 문법 형식

  • path 필수 매개변수, 문자열. 경로를 나타냅니다.
  • 파일 확장자를 나타내는 선택적 매개 변수
경로의 마지막 부분을 나타냅니다.

노드의 경로 모듈에 대한 간략한 분석

const path=require("path")

const  fpath='./a/b/c/index.html'

var fullname=path.basename(fpath)

console.log(fullname)
//获取指定后缀的文件名
const namepath=path.basename(fpath,'.html')

console.log(namepath)

2.3 path.extname()

path.extname()은 경로의 파일 확장자 이름


의 형식은 노드의 경로 모듈에 대한 간략한 분석

  • 입니다. path 필수 매개변수, 경로를 나타내는 문자열
  • 반환값: 얻은 확장자 문자열

노드의 경로 모듈에 대한 간략한 분석

const path=require("path")

const fpath='./a/b/c/d/index.html'

const ftext =path.extname(fpath)

console.log(ftext)

을 반환합니다.

3 .시계 케이스 연습


제공된 코드(한 파일에 html, css, js가 동시에 있음)
를 각각 index.html index.css index.js 3개 파일로 분할하여 In에 저장합니다. 준비된 파일

소스 코드

소스 코드를 보려면 마우스 오른쪽 버튼을 클릭하세요.

3.1 구현 단계

<style></style><script></script>
1.
태그와 일치하는 두 개의 정규 표현식을 만듭니다. 2 . 처리해야 할 HTML 파일을 읽습니다
3. index.css 스타일 파일을 작성하기 위해 resolveCSS 메소드를 사용자 정의합니다
4. index.js 스크립트 파일을 작성하기 위해solveJS 메소드를 사용자 정의합니다

5. 인덱스를 작성하기 위해 resolveHTML 메소드를 사용자 정의합니다. html 파일

3.1.1 1단계 - 필수 모듈을 가져오고 정규식을 만듭니다.

const path=require(&#39;path&#39;)
const fs=require(&#39;fs&#39;)

const regStyle=/<style>[\s\S]*<\/style>/

const scriptruler=/<script>[\s\S]*<\/script>/
//需要读取的文件
fs.readFile(path.join(__dirname,&#39;/static/index.html&#39;),&#39;utf-8&#39;,function(err,dateStr){
    if(err){
        return console.log("读取失败")
    }
   resolveCSS(dateStr)
   resolveHTML(dateStr)
   resolveJS (dateStr)
})
3.1.2 사용자 지정solveCSSsolveHTMLsolveJS 메서드

function resolveCSS(htmlStr){
    const r1=regStyle.exec(htmlStr)
    const newcss=r1[0].replace(&#39;<style>&#39;,&#39;&#39;).replace(&#39;</style>&#39;,&#39;&#39;)
    //将匹配的css写入到指定的index.css文件中
    fs.writeFile(path.join(__dirname,&#39;/static/index.css&#39;),newcss,function(err){
        if(err) return console.log("导入失败"+err.message)
        console.log("ojbk")
    })
}
function resolveJS(htmlStr){
    const r2=scriptruler.exec(htmlStr)
    const newcss=r2[0].replace(&#39;<script>&#39;,&#39;&#39;).replace(&#39;</script>&#39;,&#39;&#39;)
    //将匹配的css写入到指定的index.js文件中
    fs.writeFile(path.join(__dirname,&#39;/static/index.js&#39;),newcss,function(err){
        if(err) return console.log("导入失败"+err.message)
        console.log("ojbk")
    })
}
function  resolveHTML(htmlStr){
    const newhtml=htmlStr
    .replace(regStyle,&#39;<link rel="stylesheet" href="./index.css">&#39;)
    .replace(scriptruler,&#39;<script src="./index.js"></script>&#39;)
    //将匹配的css写入到指定的index.html文件中
    fs.writeFile(path.join(__dirname,&#39;/static/index2.html&#39;),newhtml,function(err){
        if(err) return console.log("导入失败"+err.message)
        console.log("ojbk")
    })
}

최종 결과는 스타일을 분리하는 것입니다. 지정된 파일


하지만 초기 index.html에는 모든 코드가 포함되어 있으므로

스타일을 분할해도 저장 위치는 여전히 동일하므로 최종 색인 .html의 코드는 변경되지 않습니다

노드의 경로 모듈에 대한 간략한 분석

🎜

노드 관련 지식을 더 보려면 nodejs 튜토리얼을 방문하세요!

위 내용은 노드의 경로 모듈에 대한 간략한 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 csdn.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제