当我转到路线“ / gallery”时,我从“ posts.json”文件中获取数据。我使用'fs'模块和read()
方法从文件中读取数据,然后将其写入this.pictures
数组。但是,当我导航到“ / gallery”路线时,将下载名为“ gallery”的新数据文件。
我需要从文件中读取数据并将其显示在屏幕上,而不是下载新文件:)请帮助解决此问题
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) => {
db.read();
res.send(db.pictures);
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}!`);
});
db.js:
class Database {
constructor(){
this.fs = require('fs');
this.pictures = [];
}
read() {
this.fs.readFile('./posts.json', (err, data)=> {
if(err) {
throw err;
}else {
this.pictures = data;
}
});
}
}
module.exports = Database;
答案 0 :(得分:1)
在这里,您可以看到一些错误的代码。您不应该在构造函数中调用异步方法。您是否打算仅一次或非常频繁地调用read()?我将研究NodeJS构造函数,并重述异步实践。 话虽如此,这是我可能会设置您拥有的代码的方式
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) => {
// Just call pictures. This will call read everytime it needs pictures - This may not work if you only need to call it once per app life
db.pictures(function(err,data){
if(err){
throw(err)
}else{
res.send(data)
}
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}!`);
});
db.js-这是您的应用需要更多工作的地方
const fs = require('fs')
class Database {
pictures (callback) {
return this.read(callback)
}
//Read the file from the server. Make sure to specify utf-8 to read as a string basically
read (callback) {
return fs.readFile('./posts.json', 'utf-8', (err, data) => {
if (err) {
throw err
} else {
callback(null,data)
}
})
}
}
module.exports = Database
使用诺言的另一种方式:
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) => {
db.pictures().then(data => {
res.send(data)
})
})
console.log(port)
app.listen(port, () => {
console.log(`Example app listening on port ${port}!`)
})
db.js
const fs = require('fs')
class Database {
pictures () {
return this.read()
}
read (cb) {
return new Promise((resolve, reject) => {
fs.readFile('./posts.json', 'utf-8', (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
}
module.exports = Database