从文件Express JS提供JSON服务 [英] Serving json from a file express js

查看:245
本文介绍了从文件Express JS提供JSON服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新手表示,我有一个包含db.json文件的文件夹,并且每11秒将其替换为新的db.json.让express.js提供服务以便在api调用上显示新内容的最佳方法是什么?这是我到目前为止的内容:

Newbie to express, I have a folder that has a db.json file and it gets replaced with a new db.json every 11 seceonds. What is the best way to let express.js serve it so that new content shows on api call? This is what I have so far:

const express = require('express');
const router = express.Router();

router.get('/api/items', (req, res) => {
  let dbPath = require('./data/db.json');
  res.send(JSON.stringify(dbPath));

});

db.json看起来像这样

db.json looks something like this

[{"recordType": "E90", "count": "55", "space": "4" },
{"recordType": "A48", "count": "40", "space": "5" }, ....]

问题:下次调用api时,看不到更新的值.

Problem: I'm not seeing the updated value next time I make the api call.

推荐答案

尝试一下:

const fs = require('fs');

router.get('/api/items', (req, res) => {

    fs.readFile('./data/db.json', (err, json) => {
        let obj = JSON.parse(json);
        res.json(obj);
    });

});

希望这会有所帮助

这篇关于从文件Express JS提供JSON服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆