【问题标题】:How to display data from a file on the screen?如何在屏幕上显示文件中的数据?
【发布时间】:2018-11-12 19:21:43
【问题描述】:

当我去路线“/画廊”时,我从“posts.json”文件中获取数据。使用“fs”模块和read() 方法,我从文件中读取数据,然后将其写入this.pictures 数组。但是当我导航到“/画廊”路线时,会下载名为“画廊”的新数据文件。

我需要从文件中读取数据并将其显示在屏幕上,而不是下载新文件:) 请帮助解决这个问题

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;

【问题讨论】:

  • read() 是异步的,但在调用 db.pictures() 之前无需等待它完成。如果在 res.send() 之前将 db.pictures() 记录到控制台会发生什么
  • 当我登录 db.read() 时 - 未定义当我登录 db.pictues 时 - []
  • 另外,您应该将 require(fs) 移出构造函数。所有 require 语句都缓存在节点中,因此将它放在构造函数中是没有意义的。立即启动让您和其他开发人员知道模块依赖项是什么

标签: javascript node.js express ecmascript-6 routing


【解决方案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
如果您只打算在应用程序启动时调用 read() 一次,则可以调用 readFileSync,它是您调用的文件的同步版本。因为 Node 是blocking,所以你不想在应用程序中间这样做,但它是在应用程序启动时读取配置文件等的一个选项。

使用 promises 的另一种方式:

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

【讨论】:

  • 例如更改我的代码,但屏幕上的任何结果
  • posts.json 中的数据不显示在屏幕上
  • 您是否在开发工具中看到数据返回?
  • 当我记录数据时,我在节点控制台中看到它,但在开发工具中看不到
  • 很抱歉,这是个大笨蛋。长期以来一直使用承诺,我让他们对此感到困惑。尝试新更改的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
  • 2020-11-11
  • 1970-01-01
  • 2022-06-11
相关资源
最近更新 更多