在不少時候開發的時候咱們須要導入一些外部的數據到程序當中,這些數據可能存放在csv,XML.json之類的文件當中,咱們就將其導入到程序當中,使其可以供全局進行訪問。git
private/json/city.jsonjson
[ {"code":"010","city":"北京", "pinyin": "beijing"}, {"code":"021","city":"上海", "pinyin":"shanghai"}, {"code":"0571","city":"杭州", "pinyin":"hangzhou","province": "浙江"}, {"code":"0574","city":"寧波", "pinyin":"ningbo","province": "浙江"}, {"code":"0573","city":"嘉興", "pinyin":"jiaxing","province": "浙江"}, {"code":"0575","city":"紹興", "pinyin":"shaoxing","province": "浙江"}, {"code":"0577","city":"溫州", "pinyin":"wenzhou","province": "浙江"}, {"code":"0580","city":"舟山", "pinyin":"zhoushan","province": "浙江"}, {"code":"0572","city":"湖州", "pinyin":"huzhou","province": "浙江"}, {"code":"0579","city":"金華", "pinyin":"jinhua","province": "浙江"}, {"code":"0578","city":"麗水", "pinyin":"lishui","province": "浙江"}, {"code":"0576","city":"台州", "pinyin":"taizhou","province": "浙江"}, {"code":"0570","city":"衢州", "pinyin":"quzhou","province": "浙江"}, ]
特殊注意是private文件夾的數據是不提供給客戶端api
上面的是包含城市名稱以及區號的json數據,咱們將其保存在文件當中,這裏咱們能夠經過Assets API來訪問以及處理相應的數據。ecmascript
server/main.jsui
import { Meteor } from 'meteor/meteor'; Meteor.startup(function(){ var cityList=JSON.parse(Assets.getText('json/city.json')) _.each(cityList, function(city) { console.log(city); }); })
上面的代碼會將全部的數據進行輸出,可是有的時候這些數據能夠會被其餘的項目須要,這裏咱們須要經過添加一個package來解決,同時咱們只能夠將這個包上傳到atmospherejs 咱們須要將以前的json文件移到cityjson包,最終的目錄文件以下所示this
└── cityjson ├── README.md ├── city.json ├── cityjson-tests.js ├── cityjson.js └── package.js
package.jscode
Package.describe({ name: 'wenchangshou:cityjson', version: '0.0.1', // Brief, one-line summary of the package. summary: '獲取國內的全部的城市名稱以及區號', // URL to the Git repository containing the source code for this package. git: '', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function (api) { // api.versionsFrom('1.4.2.7'); api.versionsFrom('1.0') api.export('cityList', 'server'); api.addAssets('city.json', 'server') api.addFiles('cityjson.js', 'server') }); Package.onTest(function(api) { api.use('ecmascript'); api.use('tinytest'); api.use('wenchangshou:cityjson'); api.mainModule('cityjson-tests.js'); });
cityjson.jsserver
var cityCollection=JSON.parse(Assets.getText('city.json')); cityList={city:cityCollection}
上面的操做咱們已經建立了一個可以使用的包了,這時候咱們須要將這個包上傳,方便未來的使用ip
meteor publish --createci
上傳成功以後咱們能夠直接訪問cityjson來查看咱們上傳的包,以下圖所示 ![屏幕快照 2017-02-18 下午5.37.22](http://o7ez1faxc.bkt.clouddn.com/2017-02-18-屏幕快照 2017-02-18 下午5.37.22.png)
上傳成功以後咱們將pckages/cityjson目錄刪除
rm -rf packages/cityjson
咱們在主目錄當中添加咱們上傳的包,其中wenchangshou是個人用戶名
meteor add wenchangshou:cityjson