###* 每隔一个小时从服务器下载最新的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
新闻热点
疑难解答