nodejs review-04

79 Secure your projects with HTTPS Express

  • 生成SSL证书
openssl genrsa -out privkey.pem 1023
openssl req -new -key privkey.pem -out certreq.csr
openssl x509 -req -days 3650 -in certreq.csr -signkey privkey.pem -out newcert.pem
  • 基本服务器
var fs = require('fs');
var https = require('https');
var express = require('express');
var app = express();

var options = {
  key: fs.readFileSync('privkey.pem').toString(),
  cert: fs.readFileSync('newcert.pem').toString()
};

https.createServer(options, app).listen(8080);

app.get('*', function (req, res) {
  res.end('START HTTPS');
});

81 Develop for multiple platforms

  • 不同平台的文件路径连接符号
var path = require('path');
path.sep;
  • 判断平台
process.platform 
//darwin, win32

83 Run command line scripts Unix like

  • 运行node脚本
//hello
#!/usr/bin/env node     // 正常情况下可以改成#!usr/local/bin/node
console.log('hello');

//权限
chmod 755 hello        //0755 = User:rwx Group:r-x World:r-x

//运行
./hello

86 Understand the basics of stdin stdout

  • 输入输出流
//sdin, stdout, stderr

//将输入字符串md5加密后输出
var crypto = require('crypto');

process.stdout.write('> ');
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (data) {
  if(data && data === 'q\n') {
        process.stdin.pause();
  } else if(data) {
        var h = crypto.createHash('md5');
        var s = h.update(data).digest('hex');
        console.log(s);
        process.stdout.write('> ');
  }
});

87 Launch processes with the exec function

  • child_process.exec
var exec = require('child_process').exec;

if(process.argv.length !== 3) {
        console.log('not sopport');
        process.exit(-1);
}

var cmd = process.platform === 'win32' ? 'type' : 'cat';       //注意不同平台

exec(cmd + ' ' + process.argv[2], function (err, stdout, stderr) {
  if(err) return console.log(err);
  console.log(stdout.toString('utf8'));
  console.log(stderr.toString('utf8'));
});

其他