check if required JSON is valid - node

自闭症网瘾萝莉.ら 提交于 2019-12-25 02:59:32

问题


If i require a file as

require('file.json'); 

how do i go about checking if the JSON is valid? try catch? I'm using bluebird promises so right now its just returning

 Promise.resolve(require('file.json')); 

and bluebird catches if file is not found but i also need to check the JSONs sanity. I understand you can just pass JSON.parse to a thenable if file itself is returned as a string by FS or whatever but i dont mind caching and requiring would be faster


回答1:


You are looking for the Bluebird try function. If you use resolve, the require() call may throw before its result is wrapped in a promise.

Promise.try(require, 'file.json')
Promise.try(() => require('file.json')) // Bluebird 3.0

Alternatively use

Promise.resolve('file.json').then(require)
// or
Promise.method(require)('file.json')



回答2:


The issue with

Promise.resolve(require('file.json')); 

is that it runs as

var obj = require('file.json'); 
Promise.resolve(obj); 

which means that if the require throws, the promise has no way to catch it. Instead, I'd recommend doing

new Promise(function(resolve){
    resolve(require('file.json'));
})

This executes require from inside a promise, so the thrown error will be caught properly.



来源:https://stackoverflow.com/questions/29615098/check-if-required-json-is-valid-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!