首页 > 学院 > 开发设计 > 正文

使用coffeescript定时任务下载服务器xml和plist文件解析为json

2019-11-14 11:16:12
字体:
来源:转载
供稿:网友
使用coffeescript定时每隔一个小时从服务器上下载xml和plist文件,存到本地并解析为json文件。
###* 每隔一个小时从服务器下载最新的xml和plist并解析为json###fs = require('fs')url = require('url')http = require('http')plist = require('plist')schedule = require('node-schedule')parseString = require('xml2js').parseStringinitConfig = ()->	initXMLConfig()	initPlistConfig()#下载xml并解析为Json文件initXMLConfig = () ->	file_url = "https://服务器地址/config.xml"	filepath = "./config.xml"	jsonFilepath = "./config.json"	rule = new schedule.RecurrenceRule()	#每小时的第0分钟第1秒执行	rule.second = 1	rule.minute = 0	rule.hour = [0..23]	schedule.scheduleJob(rule, ()->		options = {			host: url.parse(file_url).host,			port: 80,			path: url.parse(file_url).pathname		}		http.get(options, (res)->			if res.statusCode is 200				file = fs.createWriteStream(filepath)				res.on("data", (data)->					file.write(data)				).on("end", ()->					file.end()					file.on('finish', ()->						console.log(file_url + " downloaded success!")						xml = fs.readFileSync(filepath, 'utf-8')						if xml							parseString(xml, {explicitArray: false, ignoreAttrs: true, trim: true}, (err, result) ->								if not err									fs.writeFileSync(jsonFilepath, JSON.stringify(result), 'utf-8')									console.log("write to json success:#{jsonFilepath}")							)					)				)			else				console.log("access " + file_url + " is error, statusCode is #{res.statusCode}")		)	)#下载plist文件使用plist模块解析为jsoninitPlistConfig = () ->	file_url = "https://服务器地址/config.plist"	filepath = "./config.plist"	jsonFilepath = "./config1.json"	rule = new schedule.RecurrenceRule()	#每小时的第0分钟第10秒执行	rule.second = 10	rule.minute = 0	rule.hour = [0..23]	schedule.scheduleJob(rule, ()->		options = {			host: url.parse(file_url).host,			port: 80,			path: url.parse(file_url).pathname		}		http.get(options, (res)->			if res.statusCode is 200				file = fs.createWriteStream(filepath)				res.on('data', (data)->					file.write(data)				).on('end', ()->					file.end()					file.on('finish', ()->						console.log(file_url + " downloaded success!")						xml = fs.readFileSync(filepath, 'utf-8')						if xml							result = plist.parse(xml)							fs.writeFileSync(jsonFilepath, JSON.stringify(result), 'utf-8')							console.log("write to json success:#{jsonFilepath}")					)				)			else				console.log("access " + file_url + " is error, statusCode is #{res.statusCode}")			)		)exports.initConfig = initConfig
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表