關於nodejs的幾個乾貨(讀中文檔案編碼問題/發送郵件/定時任務)

來源:互聯網
上載者:User

標籤:

關於nodejs讀取中文檔案真是折騰了不少時間,網上各種方案,最後沒有一個適用我,好在解決了。

下面的三個知識點都是從項目中抽出的,要單獨運行指令碼的話需要用全域模式來安裝模組,比如安裝中文轉換模組(後續其它的也需要這麼做):

npm install -g iconv-lite 

npm install -g nodemailer

npm install -g node-schedule

 

1、nodejs讀取中文檔案編碼問題

準備一個文字檔(當然也可以是csv檔案等)test.txt和text.csv,nodejs檔案test.js如下:

var iconv = require(‘iconv-lite‘);var fs = require(‘fs‘);var fileStr = fs.readFileSync(‘D:\\test.csv‘, {encoding:‘binary‘});var buf = new Buffer(fileStr, ‘binary‘);var str = iconv.decode(buf, ‘GBK‘);
console.log(str);

直接讀檔案的話是亂碼,不信你可以試試。需要先統一用二進位編碼方式讀取,然後再用GBK解碼。運行結果如下:

更多參見:iconv-lite

 

2、nodejs發送郵件

啥都不想說,直接上代碼,簡單易懂:

var nodemailer = require(‘nodemailer‘);//配置郵件var transporter = nodemailer.createTransport(‘SMTP‘,{    service: ‘163qiye‘,    auth: {        user: ‘[email protected]‘,        pass: ‘123456‘,    }});//發送郵件var sendmail = function(html){    var option = {            from:"[email protected]",            to:"[email protected],[email protected]",             cc:‘[email protected]‘        }    option.subject = ‘我5年前制定的五年計劃‘    option.html= html;    transporter.sendMail(option, function(error, response){        if(error){            console.log("fail: " + error);        }else{            console.log("success: " + response.message);        }    });}//調用發送郵件sendmail("郵件內容:<br/>My goal for 2015 is to accomplish the goals of 2014 which I should have done in 2013 because I made a promise in 2012 & planned in 2011!");

更多參見:nodemailer

 

3、nodejs定時任務

這個用法很多,如果熟悉linux crontab文法,這個就更簡單了。我鄒的這個例子很和諧,呵呵:

var schedule = require(‘node-schedule‘);/*方式一:    指定某一個時間執行任務*/var schedule = require(‘node-schedule‘);var date = new Date(2014, 12, 31, 16, 1, 0);var j = schedule.scheduleJob(date, function(){    console.log(‘2015 will soon come.‘);});/*方式二:    在每個小時的多少分鐘執行*/var rule = new schedule.RecurrenceRule();rule.minute = 1;var j = schedule.scheduleJob(rule, function(){    console.log(‘I\‘m very happy now!‘);});/*方式三:    類似crontab*/var j = schedule.scheduleJob(‘1 * * * *‘, function(){    console.log(‘It\‘s time to 下午茶!‘);});

運行結果更和諧,呵呵:

不要奇怪為什麼第一個計劃任務沒有執行,因為這個是格林威治時間,它需要等8個小時後再執行。呵呵~~

更多參見:node-schedule

 

聽了一天的悲傷的音樂,越聽越開心。哈哈

 

關於nodejs的幾個乾貨(讀中文檔案編碼問題/發送郵件/定時任務)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.