【发布时间】:2020-01-18 18:25:30
【问题描述】:
我正在尝试使用JSON server 创建一个 API,从而定期以编程方式添加新数据。
目标是每小时从另一个 api 查询数据,并用这些新数据更新数据库。
目前我正在关注文档中的示例,并添加了节点 cron 模块的使用:
// index.js
var cron = require('cron').CronJob;
module.exports = () => {
const data = {
categories: []
};
const job = new cron('*/4 * * * * *', function() {
const d = new Date();
data.categories.push(d);
console.log('array updated')
});
job.start();
return data;
};
这不起作用,数组保持为空。
我想知道更新数据库的解决方案是什么样的?
我的服务器代码如下所示:
const jsonServer = require('json-server')
const fs = require('fs');
const jsonfetch = require('./index.js');
const server = jsonServer.create()
fs.writeFileSync('/tmp/db.json', JSON.stringify(jsonfetch()));
const router = jsonServer.router('/tmp/db.json')
const options = {
static: __dirname + '/public'
}
const middlewares = jsonServer.defaults(options)
const port = process.env.PORT || 3000
server.use(middlewares)
server.use('/api', router)
server.listen(port, () => {
console.log('JSON Server is running on ' + port)
})
【问题讨论】:
标签: node.js json json-server