javascript - 如何在浏览器端运行 node.js 后端脚本时定义 __dirname?
问题描述
在浏览器端运行脚本时出现错误。错误是“未捕获的 ReferenceError:__dirname 未定义”。我尝试使用 const __dirname = dirname(fileURLToPath(URL)); 在下面的查询中,但它不起作用。任何人都可以帮助解决这个问题吗?
var fs= require(['fs']);
var path= require(['path']);
dName=path.dirname;
URL=path.fileURLToPath;
//import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(URL));
var fname= "config.json"
var jPath= path.join(__dirname,"..","ConfigGen","Config",fname);
var jsString= fs.readFileSync(jPath, 'utf8')
var tType= "cto" //Get this from input
var pth= JSON.parse(jsString)[tType] //perform error handling
var cType = "jbod" //Get this from input
//Use that path
fs.readdir(pth, function(err,files) {
files.forEach(function(file){
fName= cType+"_"+tType+"_uut.yaml-example";
if(file==fName){
var flContent= fs.readFileSync(path.join(pth,file),"utf8")
console.log(flContent)
}
})
})
注意:它在节点中运行良好。在浏览器中抛出错误(我在 Chrome 中运行)
解决方案
推荐阅读
- excel - 如何获取代码以正确计算一个电子表格中的项目(变量)并成功显示此信息?
- mongodb - 将 GeoJSON 中的 OSGridRef 转换为 MongoDB 索引
- python - pycaret 上的概率与预测的标签不匹配
- python - 如何使代码以更pythonic的方式
- json - 带有listview颤动的嵌套Json
- r - 具体变量计算
- javascript - Reactjs/Nextjs 和 Mongodb 中的轮播实现在元素定义时返回错误
- reactjs - 使用不存在的值作为带有useEffect React Hook的参数时如何修复缺少的依赖警告?
- typescript - 计算一个时间段有多少个月
- xcode - 添加 DCMTK 库并为 Xcode 12.4+ 编译