javascript - 如何在屏幕上显示文件中的数据?
问题描述
当我去路线“/画廊”时,我从“posts.json”文件中获取数据。使用“fs”模块和read()
我从文件中读取数据然后将其写入this.pictures
数组的方法。但是当我导航到“/画廊”路线时,会下载名为“画廊”的新数据文件。
我需要从文件中读取数据并将其显示在屏幕上,而不是下载新文件:) 请帮助解决这个问题
应用程序.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;
解决方案
我可以在这里看到您的代码有一些问题。您在构造函数中调用了不应该的异步方法。您打算只调用一次还是非常频繁地调用 read()?我会看一下 NodeJS 的构造函数,也会复习一下异步实践。话虽如此,这就是我可能设置您拥有的代码的方式
应用程序.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}!`)
})
数据库.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
推荐阅读
- kotlin - 掌握 Kotlin 代表的窍门
- sql - Postgresql 排除基于子查询的结果
- javascript - 在 React 中访问第二层数组
- python-3.x - 将数据透视表转换为 Python 数据框
- google-sheets - Google 表格和 ImportXML - 缩小结果范围
- python - Pandas,遍历数据框项并基于列值构建新的数据框
- bash - Bash:如何存储在变量中显示带有 \n 的变量的命令
- java - Maven 测试在 Azure DevOps 中失败。java.io.FileNotFoundException:TestSuiteList.xls(没有这样的文件或目录)
- azure - Redis 锁是否应该在单独的实例上运行?
- javascript - 在 JavaScript 中,我们可以在标签中导入一个 JS 模块而不加载外部文件吗?