我不能创建一个扩展下面这个 DataRepository
类并访问其 JSON 文件中的键/值的类吗?
const fs = require("fs");
class DataRepository {
constructor(filename) {
if (!filename) {
throw new Error("Creating a repository requires a filename");
}
this.filename = filename;
try {
fs.accessSync(this.filename);
} catch (error) {
console.error("data does not exist");
}
}
async getAll() {
// Open the file called this.filename
return JSON.parse(
await fs.promises.readFile(this.filename, {
encoding: "utf-8",
})
);
}
async getOneBy(filters) {
const records = await this.getAll();
for (let record of records) {
let found = true;
for (let key in filters) {
if (record[key] !== filters[key]) {
found = false;
}
}
if (found) {
return record;
}
}
}
}
module.exports = new DataRepository("cales_data.json");
当我遇到这个错误时,这是我正在尝试的:
const fs = require("fs");
const DataRepository = require("./repositories/data");
class Address extends DataRepository {
constructor() {
this.Address = DataRepository.Address;
this.Latitude = DataRepository.Latitude;
this.Longitude = DataRepository.Longitude;
}
}
归根结底,我有一个 json 文件,它是一个对象数组,如下所示:
{
'Number (original project order)': 99,
FIELD2: null,
Code_Notes: 'Not enough room to code historic preservation approval body',
'Filler column to reference original sheet': '402 W Santa Clara St',
City: 15,
Planning_ID: 'PDC15-051',
APN: '25938036',
Total_Number_Parcels: -888,
Address: '402 W Santa Clara St',
Description_from_Agenda: 'A Planned Development Permit to allow the construction of a mixed use development with up to 1.04 million square feet for office/retail and up to 325 multi-family attached residences on a 8.93 gross acre site. ',
Census_Tract: '5008.00',
Council_District: '3',
Neighborhood_Planning_Group: '-999',
Community_Plan_Area: '-999',
Specific_Plan_Area: 'Downtown',
General_Plan_Designation: 'Downtown',
我希望能够通过 JavaScript 类访问其属性。
答案 0 :(得分:0)
正如 georg 已经指出的,您需要导出类本身才能对其进行扩展。
module.exports = DataRepository;
由于您似乎想设置一个文件名,但无论如何该文件名在模块中都是硬编码的,所以您只需在构造函数中设置即可。
class DataRepository {
constructor() {
this.filename = "cales_data.json";
try {
fs.accessSync(this.filename);
} catch (error) {
console.error("data does not exist");
}
}
...