首页 > 解决方案 > 如何在屏幕上显示文件中的数据?

问题描述

当我去路线“/画廊”时,我从“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;

标签: javascriptnode.jsexpressecmascript-6routing

解决方案


我可以在这里看到您的代码有一些问题。您在构造函数中调用了不应该的异步方法。您打算只调用一次还是非常频繁地调用 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
如果您只打算在应用程序启动时调用 read() 一次,则可以调用 readFileSync,它是您调用的文件的同步版本。因为 Node 是阻塞的,所以你不想在应用程序中间这样做,但它是在应用程序启动时读取配置文件等的一个选项。

使用承诺的另一种方式:

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


推荐阅读