Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

关于iconv-lite转换编码的问题.将utf8转为gb2312

$
0
0

我的需求是这样的:我想根据一些txt文本文件(所有txt文件都是utf8编码),和html模板文件(GB2312编码)批量生成网站,最终生成出来的就是html静态文件,且是gb2312编码的。现在的问题就是我生成出来的html文件是乱码的.不知道哪里转错误了…希望各位老师指点啊!!测试了一个上午.没效果!!!

var fs = require(“fs”), http = require(“http”), _url = require(‘url’), toEn = require(’./models/toPinyin’), newsTime = require(’./models/newsTime’), iconv = require(‘iconv-lite’);

//获取内容 function readFilesTpl(ArrKeywordsDetail) { //读取模板 var tpl, data, html; tpl = iconv.encode(fs.readFileSync(‘tpl.html’), ‘GB2312’); data = iconv.encode(fs.readFileSync(“markHtmlCore/content.txt”),‘GB2312’);

html = tpl.toString().replace(/{{content}}/, data.toString())
.replace(/{{title}}/, ArrKeywordsDetail)
.replace(/{{keywords}}/, ArrKeywordsDetail)
.replace(/{{description}}/, ArrKeywordsDetail) //description
.replace(/{{time}}/, newsTime); //description
return html;

}

//获取关键词 function readFilesKey() { var data = fs.readFileSync(“markHtmlCore/keywords.txt”, “utf-8”); return data.split(’\r\n’); }

//生成html function writeFiles(ArrKeywords) { this.ArrKeywords = ArrKeywords || [];

var p = Math.floor(Math.random() * (12 - 4) + 4) //随机段落
for(var i = 0; i < this.ArrKeywords.length; i++) {
	fs.writeFileSync('html/' + toEn(this.ArrKeywords[i]) + (i + 1) + '.html', iconv.decode(readFilesTpl(this.ArrKeywords[i]),'GB2312'))
	console.log('生成' + this.ArrKeywords[i] + "成功!");
}

}

http.createServer(function(req, res) { console.log(req.url) writeFiles(readFilesKey())

}).listen(3356, ‘127.0.0.1’); console.log(“Server running”)


Viewing all articles
Browse latest Browse all 14821

Trending Articles