프런트 엔드는 파일이 존재하는지 판단하고 얻은 js를 헤드에 수동으로 씁니다.

두 가지 방법으로 모듈에서 개발할 때 노드의 fs 모듈을 사용하여 판단하고 모듈에서 개발하지 않을 때 XMLHttpRequest 및 ActiveXObject를 사용하여 판단할 수 있습니다.

fs 모듈 사용

const fs = require('fs')
fs.exists(filePath, (exists) => {      
	if (exists) {
		console.log("文件已存在");
	} else {
	  console.log("文件不存在");
   }
});

XMLHttpRequest 및 ActiveXObject 사용

function isExistFile(filepath){
  if(filepath == null  || filepath === ""){
    return false
  }
  let xmlhttp = null
  if (window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest()
  }else{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
  }
  xmlhttp.open("GET",filepath,false)
  xmlhttp.send()
  if(xmlhttp.readyState === 4){
    if(xmlhttp.status === 200) return true //url存在
    else if(xmlhttp.status === 404) return false //url不存在
    else return false//其他状态
  }
}

Node.js는 헤드에 수동으로 작성됩니다.

function addScript(url) {
  var script = document.createElement("script")
  script.setAttribute("type", "text/javascript")
  script.setAttribute("src", url)
  document.getElementsByTagName("head")[0].appendChild(script)
}

Supongo que te gusta

Origin blog.csdn.net/qq_42563079/article/details/124188685
Recomendado
Clasificación