所以,我用快递生成器创建了一个应用框架。Bin/www服务器配置对我来说是新的。在我的应用程序中,我想访问data中的test.json文件。现在,我收到一个错误,告诉我dir不存在。我注意到了一些与我的其他应用不同的东西。我发现process.mainModule.filename包含了bin dir。我查了一下基名,就说出了"www“。真奇怪。现在我在这方面是个新手,因为我以前从来没有遇到过这样的麻烦。我发现了一些有趣的东西。
首先是错误消息:
```{错误: ENOENT:没有这样的文件或目录,打开'/Users/macbook/Documents/web-development/weather-app/bin/data/test‘
错误:-2,
code: 'ENOENT',syscall: 'open',path:'/Users/macbook/Documents/web-development/weather-app/bin/data/test'}`
1. const testPath = path.join( path.dirname(maimMod), 'data', 'test' ); // /Users/macbook/Documents/web-development/weather-app/data/test```
2. path.dirname(process.mainModule.filename), 'data', // 'city\_list.json', 'test' ); // /Users/macbook/Documents/web-development/weather-app/bin/data/test```
mainMode === p. // false -- What is going on here? Why is /bin/ excluded from the path in testPath?
Now when I try to read the test.json file I get the same result either way. I can't figure out what I am doing wrong.
Here is all the code -- I removed my api key:
```javascriptconst axios =需要量(‘axios’);
const fs =需要量(Fs);
const path =需要量(‘path’);
const = path.join(
path.dirname(process.mainModule.filename)
“数据”
//城市_list.json,
“测试”
);
const mainMod = path.dirname(process.mainModule.filename);
const testPath = path.join(
path.dirname(mainMod)
“数据”
//城市_list.json,
“测试”
);
console.log("p:",p);
Console.log(mainMod:,path.dirname(mainMod));
设结果=p === testPath;
Console.log(结果);
const getCityData = cb => {
fs.readFile(p,(err,fileContent) => {
if (err) { console.log(err); cb([]);} else { // console.log(JSON.parse(fileContent)); cb(JSON.parse(fileContent));}});
}
const getCurrentWeather = cb => {
const key =;
const cityID = '5586437';
axios.get(http://api.openweathermap.org/data/2.5/weather?id=${cityID}&appid=${key}&units=imperial)
.then(function(response) { cb(response); // console.log(response);}).catch(function(error) { console.log(error)});}
module.exports =类WeatherData {
//当前天气
静态fetchData(cb) {
getCurrentWeather(cb);}
//获取城市、州、国家以进行输入查找
静态locateCityState(cb) {
getCityData(cb);}
}
发布于 2020-09-13 16:36:02
为了其他读者的利益,快递生成器的默认项目文件结构如下所示:
|-- bin
| |-- www
|-- node_modules
|-- public
|-- routes
|-- views
|-- app.js
|-- package.json我发现process.mainModule.filename包含了bin dir。我查了一下基名,就说出了"www“。真奇怪。
我假设您正在运行一个快递生成器项目(npm start或等效的)附带的npm start脚本。如果您查看package.json,您将看到它运行node ./bin/www,这使bin/www成为您的入口点(主模块):
"scripts": {
"start": "node ./bin/www"
},那么,process.mainModule.filename === '/Users/macbook/Documents/web-development/weather-app/bin/www'.
mainMode === p. // false --这是怎么回事?为什么/bin/被排除在testPath中的路径之外?
bin被排除在testPath之外,因为您两次调用path.dirname:一次是在process.mainModule.filename上将值赋值给mainMod变量,这会删除www (代码段中的第12行),另一次是在将值分配给testPath时再次调用mainMod,后者会删除bin (第14行)。
希望这能帮上忙。
附带注意:确定“根目录”可能是脆弱和不可靠的。查看this answer的选项和它们的权衡。
发布于 2020-09-15 15:47:18
将process.mainModule保存到一个变量,然后将它传递给path.dirname()可以工作。而且,如果我没有犯一个愚蠢的错误,我早就想明白了。如果我没有犯那个小错误,我想我就不会学到那么多关于这个系统是如何工作的了。所以,这就是好处所在。我应该开一家柠檬水工厂。
https://stackoverflow.com/questions/63853343
复制相似问题