モジュールで開発する場合はノードの fs モジュールを使用して判断する方法と、モジュールで開発しない場合は XMLHttpRequest と ActiveXObject を使用して判断する 2 つの方法があります。
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//其他状态
}
}
jsを手動でheadに書き込む
function addScript(url) {
var script = document.createElement("script")
script.setAttribute("type", "text/javascript")
script.setAttribute("src", url)
document.getElementsByTagName("head")[0].appendChild(script)
}