我一直在做一个Node JS项目,一个特定的API将收到的请求正文存储到DB中。为了进行测试,我使用json-server从JSON文件中读取和写入数据。
目前,我使用经典的方法启动json-server。
json-server --watch ./datastore/cion-config-datastore.json --port 9000
限制是,仅当满足一组特定条件时,API才应将请求正文写入json文件。因此,我不希望json-server始终在后台运行,只希望在需要时才调用它。
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的解决方案,我们将不胜感激。
发布于 2019-12-08 22:42:27
你应该看看module child_process
const { spawn } = require('child_process');
const json_server = spawn('json-server',
['--watch', './datastore/cion-config-datastore.json', '--port', '9000']);考虑将路径更改为绝对路径。
确保不要多次启动json-server。幸运的时候,它会拒绝多次启动,因为端口已经被另一个实例占用了。
https://stackoverflow.com/questions/59233575
复制相似问题