首页 > 解决方案 > 如何在浏览器端运行 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 中运行)

标签: javascriptnode.js

解决方案


推荐阅读