'use strict';
//main.js文件
//包含字符串、数组、日期、加解密等常见功能。
// 引入hello模块:
var greet = require('./hello');
var fs = require('fs');
//crypto模块的目的是为了提供通用的加密和哈希算法。用纯JavaScript代码实现这些功能不是不可能,但速度会非常慢。Nodejs用C/C++实现这些算法后,通过cypto这个模块暴露给JavaScript接口,这样用起来方便,运行速度也快。
const crypto = require('crypto');
var s = 'Michael';
var arr = [1, 2, 3.14, 'Hello', null, true];
//创建数组
var arr1= new Array("1", "2", "3","adjsak"); // 创建了数组[1, 2, 3]
var arr11= new Array(1,2,3,4);
//转义字符
var string1 = '\u4e2d\u6587';
var sr = `adhaWa`.toUpperCase(); // 返回'HELLO'
var srr = `dafaDSAFAAF`.toLocaleLowerCase();
greet(s); // Hello, Michael!
console.log(arr[4]);
console.log(arr1[3]);
console.log("arr11[3]=" + arr11[3]);
//对象定义和使用
var person = {
name: 'Bob',
age: 20,
tags: ['js', 'web', 'mobile'],
city: 'Beijing',
hasCar: true,
zipcode: null,
address:"beijing"
};
if(person.hasOwnProperty("name")){
console.log("true");
}else{
console.log("false");
}
if(person.hasOwnProperty("add")){
console.log("true");
}else{
console.log("false");
}
//解构赋值
var {name, age, address} = person;
console.log('name = ' + name + ', age = ' + age + ', address = ' + address);
console.log(person.address);
console.log(string1);
//多行定义
var string2 = `这是一个
多行
字符串`;
console.log(string2);
//拼接字符串
var name = '小明';
var age = 20;
var message = `你好, ${name}, 你今年${age}岁了!`;
// alert(message);
console.log(message);
console.log(sr);
console.log(srr);
//获取索引
var s = 'hello, world';
var index = s.indexOf('world'); // 返回7
s.indexOf('World'); // 没有找到指定的子串,返回-1
console.log(index);
//截取部分
var s = 'hello, world'
var sub = s.substring(0, 5); // 从索引0开始到5(不包括5),返回'hello'
s.substring(7); // 从索引7开始到结束,返回'world'
console.log(sub);
//数组复制
var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
var aCopy = arr.slice();
console.log(aCopy);
//添加和删除,数组的各种操作
var arr = [1, 2];
arr.push('A', 'B'); // 返回Array新的长度: 4
console.log(arr);
arr.pop(); // pop()
console.log(arr);
arr.pop(); // pop()
console.log(arr);
//1,2
arr.unshift('A', 'B'); // 返回Array新的长度: 4
console.log(arr);
arr.shift();
console.log(arr);
arr.sort();
console.log(arr);
arr.reverse();
console.log(arr);
var arr1 = ['Microsoft', 'Apple', 'Yahoo', 'AOL', 'Excite', 'Oracle'];
// 从索引2开始删除3个元素,然后再添加两个元素:
arr1.splice(2, 3, 'Google', 'Facebook'); // 返回删除的元素 ['Yahoo', 'AOL', 'Excite']
console.log(arr1); // ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']
// 只删除,不添加:
arr1.splice(2, 2); // ['Google', 'Facebook']
console.log(arr1); // ['Microsoft', 'Apple', 'Oracle']
// 只添加,不删除:
arr1.splice(2, 0, 'Google', 'Facebook'); // 返回[],因为没有删除任何元素
console.log(arr1);// ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']
var arr2 = arr.concat(arr1);
console.log(arr2);
arr.join('-');
console.log(arr.join('-'));
//二维数组
var arr3 = [[1, 2, 3], [400, 500, 600], '-'];
console.log(arr3);
console.log(arr3[1][1]);
console.log(arr3[2][1]);
var o = {
name: 'Jack',
age: 20,
city: 'Beijing'
};
for (var key in o) {
if (o.hasOwnProperty(key)) {
console.log(o[key]); // 'name', 'age', 'city'
}
}
//map
var m = new Map(); // 空Map
m.set('Adam', 67); // 添加新的key-value
m.set('Bob', 59);
m.has('Adam'); // 是否存在key 'Adam': true
m.get('Adam'); // 67
//m.delete('Adam'); // 删除key 'Adam'
m.get('Adam'); // undefined
console.log(m.get('Adam'));
m.forEach(function (element, index, array) {
// element: 指向当前元素的值
// index: 指向当前索引
// array: 指向Array对象本身
console.log(element + ', index = ' + index);
});
console.log(m);
function buildDate({year, month, day, hour=0, minute=0, second=0}) {
return new Date(year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
}
var date = buildDate({ year: 2018, month: 2, day: 3 });
var date = buildDate({ year: 2016, month: 3, day: 1, hour: 1, minute: 15 });
console.log(date1);
//北京时区时间和utc时间
var d = new Date();
var d1= d.toLocaleString(); // '2015/6/24 下午7:49:22',本地时间(北京时区+8:00),显示的字符串与操作系统设定的格式有关
var d2= d.toUTCString(); // 'Wed, 24 Jun 2015 11:49:22 GMT',UTC时间,与本地时间相差8小时
console.log(d1);
console.log(d2);
var timeStr= "2017-11-09 23:23:23"
var time=new Date('2018-09-13 0:00:00');
console.log(time);
var xiaoming = {
name: '小明',
birth: 1990,
age: function () {
var y = new Date().getFullYear();
return y - this.birth;
}
};
var fn = xiaoming.age();
console.log(fn);
//高阶函数
function add(x, y, f) {
return f(x) + f(y);
}
var add = add(-5, 6, Math.abs);
console.log(add);
function pow(x) {
return x * x;
}
var arr = [ 6, 7, 8, 9,10,1, 2, 3, 4, 5];
var results = arr.map(pow); // [1, 4, 9, 16, 25, 36, 49, 64, 81]
console.log(results);
//自定义排序
arr.sort(function (x, y) {
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
});
console.log(arr); // [1, 2, 10, 20]
var arr = ['Google', 'apple', 'Microsoft'];
arr.sort(function (s1, s2) {
var x1 = s1.toUpperCase();
var x2 = s2.toUpperCase();
if (x1 < x2) {
return -1;
}
if (x1 > x2) {
return 1;
}
return 0;
}); // ['apple', 'Google', 'Microsoft']
//闭包
console.log(arr); // [1, 2, 10, 20]
function count() {
var arr = [];
for (var i=1; i<=3; i++) {
arr.push(function () {
return i * i;
});
}
return arr;
}
function count() {
var arr = [];
for (var i=1; i<=3; i++) {
arr.push(
(function (n) {
return function () {
return n * n;
}
}
)(i));
}
return arr;
}
var results = count();
var f1 = results[0];
var f2 = results[1];
var f3 = results[2];
console.log(f1());
console.log(f2());
console.log(f3());
//箭头函数,es6新加入的语法
var obj = {
birth: 1990,
getAge: function () {
var b = this.birth; // 1990
var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
return fn();
}
};
obj.getAge(); // 25
console.log(obj.getAge());
var obj1 = {
birth: 1990,
getAge: function (year) {
var b = this.birth; // 1990
var fn = (x) => x - this.birth; // this.birth仍是1990
return fn.call({birth:2000}, year);
}
};
console.log(obj1.getAge(2015));
//著名的斐波那契数列
function fib(max) {
var
t,
a = 0,
b = 1,
arr = [0, 1];
while (arr.length < max) {
[a, b] = [b, a + b];
arr.push(b);
}
return arr;
}
console.log(fib(10));
//generator
function* fib1(max) {
var
t,
a = 0,
b = 1,
n = 0;
while (n < max) {
yield a;
[a, b] = [b, a + b];
n ++;
}
return;
}
for (var x of fib1(10)) {
console.log(x); // 依次输出0, 1, 1, 2, 3, ...
}
var xiaoming = {
name: '小明',
age: 14,
gender: true,
height: 1.65,
grade: null,
'middle-school': '\"W3C\" Middle School',
skills: ['JavaScript', 'Java', 'Python', 'Lisp']
};
//var s = JSON.stringify(xiaoming);
//JSON.stringify(xiaoming, null, ' ');
var s = JSON.stringify(xiaoming, ['name', 'skills'], ' ');
console.log(s);
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json';
// 从远程地址获取JSON:
// $.getJSON(url, function (data) {
// // 获取结果:
// var city = data.query.results.channel.location.city;
// var forecast = data.query.results.channel.item.forecast;
// var result = {
// city: city,
// forecast: forecast
// };
// alert(JSON.stringify(result, null, ' '));
// });
// 导入http模块:
//var http = require('http');
// 创建http server,并传入回调函数:
//var server = http.createServer(function (request, response) {
// 回调函数接收request和response对象,
// 获得HTTP请求的method和url:
// console.log(request.method + ': ' + request.url);
// 将HTTP响应200写入response, 同时设置Content-Type: text/html:
// response.writeHead(200, {'Content-Type': 'text/html'});
// 将HTTP响应的HTML内容写入response:
// response.end('<h1>Hello world!</h1>');
//});
// 让服务器监听8080端口:
//server.listen(8080);
//console.log('Server is running at http://127.0.0.1:8080/');
//异步代码
// fs.readFile('xiaoming.json', 'utf-8', function (err, data) {
// if (err) {
// console.log(err);
// } else {
// console.log(data);
// }
// });
//流
// fs.stat('xiaoming.json', function (err, stat) {
// if (err) {
// console.log(err);
// } else {
// // 是否是文件:
// console.log('isFile: ' + stat.isFile());
// // 是否是目录:
// console.log('isDirectory: ' + stat.isDirectory());
// if (stat.isFile()) {
// // 文件大小:
// console.log('size: ' + stat.size);
// // 创建时间, Date对象:
// console.log('birth time: ' + stat.birthtime);
// // 修改时间, Date对象:
// console.log('modified time: ' + stat.mtime);
// }
// }
// });
//自动从xiaoming.json写入copied.txt中
//var rs = fs.createReadStream('xiaoming.json');
//var ws = fs.createWriteStream('copied.txt');
//rs.pipe(ws);
//aes对称密钥加解密
function aesEncrypt(data, key) {
const cipher = crypto.createCipher('aes-256-cbc', key);
var crypted = cipher.update(data, 'utf8', 'base64');
crypted += cipher.final('base64');
return crypted;
}
function aesDecrypt(encrypted, key) {
const decipher = crypto.createDecipher('aes-256-cbc', key);
var decrypted = decipher.update(encrypted, 'base64', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
var data = 'Hello, this is a secret message!';
var key = 'Password!';
var encrypted = aesEncrypt(data, key);
var decrypted = aesDecrypt(encrypted, key);
console.log('Plain text: ' + data);
console.log('Encrypted text: ' + encrypted);
console.log('Decrypted text: ' + decrypted);
//rsa非对称加解密
// 从文件加载key:
function loadKey(file) {
// key实际上就是PEM编码的字符串:
return fs.readFileSync(file, 'utf8');
}
let prvKey = loadKey('./rsa-prv.pem');
let pubKey = loadKey('./rsa-pub.pem');
let message1 = 'Hello, world!';
//使用私钥加密,公钥解密
// 使用私钥加密:
let enc_by_prv = crypto.privateEncrypt(prvKey, Buffer.from(message1, 'utf8'));
//console.log('encrypted by private key: ' + enc_by_prv.toString('hex'));
//使用公钥解密:
let dec_by_pub = crypto.publicDecrypt(pubKey, enc_by_prv);
//console.log('decrypted by public key: ' + dec_by_pub.toString('utf8'));
//使用公钥加密,私钥解密
// 使用公钥加密:
let enc_by_pub = crypto.publicEncrypt(pubKey, Buffer.from(message1, 'utf8'));
//console.log('encrypted by public key: ' + enc_by_pub.toString('hex'));
// 使用私钥解密:
let dec_by_prv = crypto.privateDecrypt(prvKey, enc_by_pub);
//console.log('decrypted by private key: ' + dec_by_prv.toString('utf8'));
function Student(name) {
this.name = name;
// this.hello = function () {
// console.log('Hello, ' + this.name + '!');
// }
}
Student.prototype.hello = function () {
console.log('Hello, ' + this.name + '!');
};
var xiaoming = new Student("xiaoming");
var xiaohu = new Student("xiaohu");
console.log(xiaoming.name);
console.log(xiaoming.hello());
console.log(xiaohu.name);
console.log(xiaohu.hello());