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

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

青灯夜游
青灯夜游앞으로
2022-05-26 13:00:121924검색

이 글은 node의 경로 모듈을 안내하고, 경로 내장 모듈의 일부 API를 소개하고, 실습 사례도 준비한 내용이 모든 분들께 도움이 되기를 바랍니다.

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

1. 경로 모듈에 대한 첫 소개

path 모듈은 Node.js에서 공식적으로 제공하는 모듈이며 경로 처리

에 사용됩니다. 경로 처리에 대한 사용자의 요구 사항을 충족하기 위해 일련의 메서드와 속성을 제공합니다.

2.path 모듈 API

2.1 path.join()

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

구문 형식은

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

...paths(string) 경로 조각의 시퀀스는 연결해야 하는 모든 경로 시리즈입니다.

반환된 값은 string

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

console.log(pathStr)
노드의 경로 모듈의 일부 API에 대한 간략한 분석

2.2 path.basename()

입니다.

path.basename() 메서드를 사용하여 경로의 마지막 부분을 가져옵니다. 이 메서드는 경로에서 파일 이름을 가져오는 데 자주 사용됩니다.

구문 형식

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

  • 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)

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

2.3 path.extname()

path.extname()은 파일 확장자

의 형식은

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

  • 입니다. path는 필수 매개변수이며 경로를 나타내는 문자열입니다.

  • 반환값: 얻은 확장자 문자열

const path=require("path")

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

const ftext =path.extname(fpath)

console.log(ftext)

노드의 경로 모듈의 일부 API에 대한 간략한 분석을 반환합니다.

3. 시계 사례 연습

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

소스 코드:http://127.0.0.1:5500/node/day1/static/index.html

3.1 구현 단계

1 두 개의 정규 표현식 만들기 표현식은 일치하는 데 사용됩니다. <style></style><script></script> 태그
2. fs 모듈을 사용하여 처리해야 하는 HTML 파일을 읽습니다.
3. findCSS 메서드를 사용자 정의하여 index.css 스타일 파일을 작성합니다.
4. 해결JS 메서드를 사용자 정의하여 작성합니다. index.js 스크립트 파일을 입력합니다.
5. index.html 파일을 작성하기 위해 ResolveHTML 메소드를 사용자 정의

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 사용자 정의 learnCSSsolveHTMLsolveJS 메소드

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")
    })
}

The 최종 결과는 지정된 파일의 스타일을 제거하는 것입니다

하지만 초기 index.html에는 모든 코드가 포함되어 있으며, 그 다음
은 스타일이 분할될 때 스타일이 저장되는 위치이므로 여전히 원본이므로 최종입니다. index.html 코드는 변경되지 않습니다.

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

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

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

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