首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何动态启动json-server

如何动态启动json-server
EN

Stack Overflow用户
提问于 2019-12-08 16:08:43
回答 1查看 1.4K关注 0票数 0

我一直在做一个Node JS项目,一个特定的API将收到的请求正文存储到DB中。为了进行测试,我使用json-server从JSON文件中读取和写入数据。

目前,我使用经典的方法启动json-server。

json-server --watch ./datastore/cion-config-datastore.json --port 9000

限制是,仅当满足一组特定条件时,API才应将请求正文写入json文件。因此,我不希望json-server始终在后台运行,只希望在需要时才调用它。

代码语言:javascript
复制
app.post('/someapi',(req,res)=>{

    var someValue = req.body

    if(condition) // check the condition
    {
         // then start the json-server to watch the JSON file
    }

})

如果我使用经典的启动json-server的方法,那么每次都必须手动启动它,即使不是必需的。

如果有人能提出一个动态调用json-server的解决方案,我们将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2019-12-08 22:42:27

你应该看看module child_process

代码语言:javascript
复制
const { spawn } = require('child_process');
const json_server = spawn('json-server',
    ['--watch', './datastore/cion-config-datastore.json', '--port', '9000']);

考虑将路径更改为绝对路径。

确保不要多次启动json-server。幸运的时候,它会拒绝多次启动,因为端口已经被另一个实例占用了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59233575

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档