The front end judges whether the file exists, and manually writes the obtained js into the head

In two ways, when developing in a module, you can use node's fs module to judge, when not developing in a module, use XMLHttpRequest and ActiveXObject to judge

Use the fs module

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

Using XMLHttpRequest and 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//其他状态
  }
}

js is manually written into the head

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

Guess you like

Origin blog.csdn.net/qq_42563079/article/details/124188685
Recommended