【发布时间】:2018-11-12 14:50:37
【问题描述】:
当我去路由'/gallery' 时,我想从文件“posts.json”接收数据。
我使用fs 模块从文件中获取数据,并使用read() 方法从文件“posts.json”中读取数据。
因此,我收到错误:'ReferenceError: fs is not defined'
当使用fs 模块在路由'/gallery' 中导航时,如何从文件“posts.json”中显示数据?
app.js:
const express = require('express');
const Database = require('./db');
const app = express();
const port = 3000;
const db = new Database();
app.use(express.json());
app.get('/gallery', (req, res) => {
const items = db.read();
res.send(items);
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}!`);
});
db.js:
class Database {
constructor(){
this.fs = require('fs');
this.pictures = [];
}
read() {
fs.readFile('./posts.json', (err, data)=> {
if(err) {
throw err;
}else {
return this.pictures = data;
}
});
}
}
module.exports = Database;
【问题讨论】:
-
你写的是 fs.readFile 而不是 THIS.fs
标签: javascript node.js express ecmascript-6 server