nodejs学习日记1
# REPL(交互式解释器)
Node.js REPL(Read Eval Print Loop:交互式解释器) 表示一个电脑的环境,类似 Window 系统的终端或 Unix/Linux shell,我们可以在终端中输入命令,并接收系统的响应。 Node 自带了交互式解释器,可以执行以下任务:
- 读取 - 读取用户输入,解析输入了Javascript 数据结构并存储在内存中。
- 执行 - 执行输入的数据结构
- 打印 - 输出结果
- 循环 - 循环操作以上步骤直到用户两次按下 ctrl-c 按钮退出。
Node 的交互式解释器可以很好的调试 Javascript 代码。 开始学习 REPL 我们可以输入以下命令来启动 Node 的终端:
$ node
>
2
这时我们就可以在 > 后输入简单的表达式,并按下回车键来计算结果。
# 简单的表达式运算
接下来让我们在 Node.js REPL 的命令行窗口中执行简单的数学运算:
$ node
> 1 +4
5
> 5 / 2
2.5
> 3 * 6
18
> 4 - 1
3
> 1 + ( 2 * 3 ) - 4
3
>
2
3
4
5
6
7
8
9
10
11
12
# 使用变量
你可以将数据存储在变量中,并在你需要的时候使用它。 变量声明需要使用 var 关键字,如果没有使用 var 关键字变量会直接打印出来。 使用 var 关键字的变量可以使用 console.log() 来输出变量。
$ node
> x = 10
10
> var y = 10
undefined
> x + y
20
> console.log("Hello World")
Hello World
undefined
> console.log("www.runoob.com")
www.runoob.com
undefined
2
3
4
5
6
7
8
9
10
11
12
13
# 多行表达式
Node REPL 支持输入多行表达式,这就有点类似 JavaScript。接下来让我们来执行一个 do-while 循环:
$ node
> var x = 0
undefined
> do {
... x++;
... console.log("x: " + x);
... } while ( x < 5 );
x: 1
x: 2
x: 3
x: 4
x: 5
undefined
>
2
3
4
5
6
7
8
9
10
11
12
13
14
... 三个点的符号是系统自动生成的,你回车换行后即可。Node 会自动检测是否为连续的表达式。
# 下划线(_)变量
你可以使用下划线(_)获取上一个表达式的运算结果:
$ node
> var x = 10
undefined
> var y = 20
undefined
> x + y
30
> var sum = _
undefined
> console.log(sum)
30
undefined
>
2
3
4
5
6
7
8
9
10
11
12
13
# REPL 命令
ctrl + c - 退出当前终端。 ctrl + c 按下两次 - 退出 Node REPL。 ctrl + d - 退出 Node REPL. 向上/向下 键 - 查看输入的历史命令 tab 键 - 列出当前命令 .help - 列出使用命令 .break - 退出多行表达式 .clear - 退出多行表达式 .save filename - 保存当前的 Node REPL 会话到指定文件 .load filename - 载入当前 Node REPL 会话的文件内容。
# 控制台
保存日志的方法
node x.console.log.js > 1.log
node app 1>app.log 2>&1 或者 1>app.log 2>app.err
日志重定向
# new Console(stdout[, stderr])#
- stdout <stream.Writable>
- stderr <stream.Writable> Creates a new Console with one or two writable stream instances. stdout is a writable stream to print log or info output. stderr is used for warning or error output. If stderr is not provided, stdout is used for stderr.
const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
const count = 5;
logger.log('count: %d', count);
// in stdout.log: count 5
2
3
4
5
6
7
8
The global console is a special Console whose output is sent to process.stdout and process.stderr. It is equivalent to calling:
new Console(process.stdout, process.stderr);
# console.count([label])#
Added in: v8.3.0
- label
<string>
The display label for the counter. Defaults to 'default'. Maintains an internal counter specific to label and outputs to stdout the number of times console.count() has been called with the given label.
> console.count()
default: 1
undefined
> console.count('default')
default: 2
undefined
> console.count('abc')
abc: 1
undefined
> console.count('xyz')
xyz: 1
undefined
> console.count('abc')
abc: 2
undefined
> console.count()
default: 3
undefined
>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# console.dir(obj[, options])#
Added in: v0.1.101
- obj
<any>
- options
<Object>
- showHidden
<boolean>
- depth
<number>
- colors
<boolean>
Uses util.inspect() on obj and prints the resulting string to stdout. This function bypasses any custom inspect() function defined on obj. An optional options object may be passed to alter certain aspects of the formatted string:
- showHidden
showHidden - if true then the object's non-enumerable and symbol properties will be shown too. Defaults to false.
depth - tells util.inspect() how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. Defaults to 2. To make it recurse indefinitely, pass null.
colors - if true, then the output will be styled with ANSI color codes. Defaults to false. Colors are customizable; see customizing util.inspect() colors.
// 一:页面代码
console.log("log信息");
//在页面中执行(node app.js)这个文件会在控制台中看到log信息:"log信息"
//换个方式执行:node app.js 1>info.txt(1代表重定向标准输出流);
//这个时候会在app.js的同级目录下看到一个info.txt文件,里面还有"log信息".
//二:依次序输出所有字符串
console.log("%s","first","second");
//输出结果:first second
//三.将对象转换为普通字符串后执行
console.log("%s","guoyansi",{name:"思思博士"});
//输出结果:guoyansi { name: '思思博士' }
//四:
//将字符串作为数值进行转换
console.log("%d","25.6");
//输出结果:25.6
console.log("%d","guoyansi");
//输出结果:guoyansi
//五 输出%
console.log("%%");
//输出结果:%
console.log("%%","gys");
//输出结果:% gys
//六 将console.error信息输出到文件中去
//页面代码:
console.error("guoyansi is error");
//利用node app.js 2>err.txt启动这个页面
//会在同级目录下多一个err.txt文件.文件里面还有"guoyansi is error"
//七 直接在命令行启动一个并不存在的文件javascript.js,这样:
// node javascript.js 2>info.txt
//输出结果:会在命令行所在的目录下多出一个文件info.txt;
//info.txt文件中的内容如下
/*
module.js:340
throw err;
^
Error: Cannot find module 'E:\node\gys\javascript.js'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
*/
//八:console.warn的用法和console.error()用法一样
//九:console.time()和console.timeEnd()输出中间代码的执行时间(注意:time和timeEnd的参数必须完全一致)
console.time("for循环的时间:")
var a=0;
for(var i=0;i<10000000000000;i++){
a++;
}
console.timeEnd("for循环的时间:")
/*
* 10.console.trace()方法将当前位置处的栈信息作为标准错误信息进行输出.
* */
var obj={
name:"guoyansi",
age:23,
eat:function(){}
}
console.trace(obj);
//输出结果:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# 缓存区Buffer
JavaScript 语言自身只有字符串数据类型,没有二进制数据类型。 但在处理像TCP流或文件流时,必须使用到二进制数据。因此在 Node.js中,定义了一个 Buffer 类,该类用来创建一个专门存放二进制数据的缓存区。 在 Node.js 中,Buffer 类是随 Node 内核一起发布的核心库。Buffer 库为 Node.js 带来了一种存储原始数据的方法,可以让 Node.js 处理二进制数据,每当需要在 Node.js 中处理I/O操作中移动的数据时,就有可能使用 Buffer 库。原始数据存储在 Buffer 类的实例中。一个 Buffer 类似于一个整数数组,但它对应于 V8 堆内存之外的一块原始内存。
var bf1 = new Buffer("a")
var bf2 = new Buffer("b")
var bf3 = new Buffer("c")
var r = Buffer.concat([bf1,bf2,bf3])
console.log(r)
r.toString()
2
3
4
5
6
7
# 创建 Buffer 类
- Buffer 提供了以下 API 来创建 Buffer 类:
- Buffer.alloc(size[, fill[, encoding]]): 返回一个指定大小的 Buffer 实例,如果没有设置 fill,则默认填满 0
- Buffer.allocUnsafe(size): 返回一个指定大小的 Buffer 实例,但是它不会被初始化,所以它可能包含敏感的数据
- Buffer.allocUnsafeSlow(size)
- Buffer.from(array): 返回一个被 array 的值初始化的新的 Buffer 实例(传入的 array 的元素只能是数字,不然就会自动被 0 覆盖)
- Buffer.from(arrayBuffer[, byteOffset[, length]]): 返回一个新建的与给定的 ArrayBuffer 共享同一内存的 Buffer。
- Buffer.from(buffer): 复制传入的 Buffer 实例的数据,并返回一个新的 Buffer 实例
- Buffer.from(string[, encoding]): 返回一个被 string 的值初始化的新的 Buffer 实例
Node.js 目前支持的字符编码包括:
- ascii - 仅支持 7 位 ASCII 数据。如果设置去掉高位的话,这种编码是非常快的。
- utf8 - 多字节编码的 Unicode 字符。许多网页和其他文档格式都使用 UTF-8 。
- utf16le - 2 或 4 个字节,小字节序编码的 Unicode 字符。支持代理对(U+10000 至 U+10FFFF)。
- ucs2 - utf16le 的别名。
- base64 - Base64 编码。
- latin1 - 一种把 Buffer 编码成一字节编码的字符串的方式。
- binary - latin1 的别名。
- hex - 将每个字节编码为两个十六进制字符。
# 写入缓冲区
- 语法
写入 Node 缓冲区的语法如下所示: buf.write(string[, offset[, length]][, encoding])
# 参数
参数描述如下:
- string - 写入缓冲区的字符串。
- offset - 缓冲区开始写入的索引值,默认为 0 。
- length - 写入的字节数,默认为 buffer.length
- encoding - 使用的编码。默认为 'utf8' 。
根据 encoding 的字符编码写入 string 到 buf 中的 offset 位置。 length 参数是写入的字节数。 如果 buf 没有足够的空间保存整个字符串,则只会写入 string 的一部分。 只部分解码的字符不会被写入。
# 返回值
返回实际写入的大小。如果 buffer 空间不足, 则只会写入部分字符串。
buf = Buffer.alloc(256);
len = buf.write("www.runoob.com");
console.log("写入字节数 : "+ len);
2
3
4
# 缓冲区读取数据
# 语法
读取 Node 缓冲区数据的语法如下所示: buf.toString([encoding[, start[, end]]])
# 参数
参数描述如下:
- encoding - 使用的编码。默认为 'utf8' 。
- start - 指定开始读取的索引位置,默认为 0。
- end - 结束位置,默认为缓冲区的末尾。
# 返回值
解码缓冲区数据并使用指定的编码返回字符串。
参考文档Node.js Buffer(缓冲区) (opens new window)
# 模块和包
代码运行时会变成
function(exports,require,module,__filename,__dirname){
var sum = function(a,b){
return a + b;
}
exports.sum = sum;
return module.exports;
}
2
3
4
5
6
7
//exports 默认导出对象 //require 是加载其它模块的方法 //module代表当前的模块对象module.exports //__filename 是当前模块的绝对路径 //_dirname 是当前模块的绝对目录
代码块的引用
var sum = require("sum");
// 查找模块 会在当前目录的node_modules目录中查找sum文件夹 里面的index.js
// 也可以在package.json 中设置main 来指定文件地址
// 放置到node_modules中比指定路径会更加灵活
console.log(sum(1,2));
console.log(__filename);
console.log(__dirname);
2
3
4
5
6
7
8
9
# 内置模块
内置模块很多,具体参考v8文档 (opens new window)
# 内置模块fs
# 文件模块方法参考手册
序号 方法 & 描述
1 fs.rename(oldPath, newPath, callback)
异步 rename().回调函数没有参数,但可能抛出异常。
2 fs.ftruncate(fd, len, callback)
异步 ftruncate().回调函数没有参数,但可能抛出异常。
3 fs.ftruncateSync(fd, len)
同步 ftruncate()
4 fs.truncate(path, len, callback)
异步 truncate().回调函数没有参数,但可能抛出异常。
5 fs.truncateSync(path, len)
同步 truncate()
6 fs.chown(path, uid, gid, callback)
异步 chown().回调函数没有参数,但可能抛出异常。
7 fs.chownSync(path, uid, gid)
同步 chown()
8 fs.fchown(fd, uid, gid, callback)
异步 fchown().回调函数没有参数,但可能抛出异常。
9 fs.fchownSync(fd, uid, gid)
同步 fchown()
10 fs.lchown(path, uid, gid, callback)
异步 lchown().回调函数没有参数,但可能抛出异常。
11 fs.lchownSync(path, uid, gid)
同步 lchown()
12 fs.chmod(path, mode, callback)
异步 chmod().回调函数没有参数,但可能抛出异常。
13 fs.chmodSync(path, mode)
同步 chmod().
14 fs.fchmod(fd, mode, callback)
异步 fchmod().回调函数没有参数,但可能抛出异常。
15 fs.fchmodSync(fd, mode)
同步 fchmod().
16 fs.lchmod(path, mode, callback)
异步 lchmod().回调函数没有参数,但可能抛出异常。Only available on Mac OS X.
17 fs.lchmodSync(path, mode)
同步 lchmod().
18 fs.stat(path, callback)
异步 stat(). 回调函数有两个参数 err, stats,stats 是 fs.Stats 对象。
19 fs.lstat(path, callback)
异步 lstat(). 回调函数有两个参数 err, stats,stats 是 fs.Stats 对象。
20 fs.fstat(fd, callback)
异步 fstat(). 回调函数有两个参数 err, stats,stats 是 fs.Stats 对象。
21 fs.statSync(path)
同步 stat(). 返回 fs.Stats 的实例。
22 fs.lstatSync(path)
同步 lstat(). 返回 fs.Stats 的实例。
23 fs.fstatSync(fd)
同步 fstat(). 返回 fs.Stats 的实例。
24 fs.link(srcpath, dstpath, callback)
异步 link().回调函数没有参数,但可能抛出异常。
25 fs.linkSync(srcpath, dstpath)
同步 link().
26 fs.symlink(srcpath, dstpath[, type], callback)
异步 symlink().回调函数没有参数,但可能抛出异常。 type 参数可以设置为 'dir', 'file', 或 'junction' (默认为 'file') 。
27 fs.symlinkSync(srcpath, dstpath[, type])
同步 symlink().
28 fs.readlink(path, callback)
异步 readlink(). 回调函数有两个参数 err, linkString。
29 fs.realpath(path[, cache], callback)
异步 realpath(). 回调函数有两个参数 err, resolvedPath。
30 fs.realpathSync(path[, cache])
同步 realpath()。返回绝对路径。
31 fs.unlink(path, callback)
异步 unlink().回调函数没有参数,但可能抛出异常。
32 fs.unlinkSync(path)
同步 unlink().
33 fs.rmdir(path, callback)
异步 rmdir().回调函数没有参数,但可能抛出异常。
34 fs.rmdirSync(path)
同步 rmdir().
35 fs.mkdir(path[, mode], callback)
S异步 mkdir(2).回调函数没有参数,但可能抛出异常。 mode defaults to 0777.
36 fs.mkdirSync(path[, mode])
同步 mkdir().
37 fs.readdir(path, callback)
异步 readdir(3). 读取目录的内容。
38 fs.readdirSync(path)
同步 readdir().返回文件数组列表。
39 fs.close(fd, callback)
异步 close().回调函数没有参数,但可能抛出异常。
40 fs.closeSync(fd)
同步 close().
41 fs.open(path, flags[, mode], callback)
异步打开文件。
42 fs.openSync(path, flags[, mode])
同步 version of fs.open().
43 fs.utimes(path, atime, mtime, callback)
44 fs.utimesSync(path, atime, mtime)
修改文件时间戳,文件通过指定的文件路径。
45 fs.futimes(fd, atime, mtime, callback)
46 fs.futimesSync(fd, atime, mtime)
修改文件时间戳,通过文件描述符指定。
47 fs.fsync(fd, callback)
异步 fsync.回调函数没有参数,但可能抛出异常。
48 fs.fsyncSync(fd)
同步 fsync.
49 fs.write(fd, buffer, offset, length[, position], callback)
将缓冲区内容写入到通过文件描述符指定的文件。
50 fs.write(fd, data[, position[, encoding]], callback)
通过文件描述符 fd 写入文件内容。
51 fs.writeSync(fd, buffer, offset, length[, position])
同步版的 fs.write()。
52 fs.writeSync(fd, data[, position[, encoding]])
同步版的 fs.write().
53 fs.read(fd, buffer, offset, length, position, callback)
通过文件描述符 fd 读取文件内容。
54 fs.readSync(fd, buffer, offset, length, position)
同步版的 fs.read.
55 fs.readFile(filename[, options], callback)
异步读取文件内容。
56 fs.readFileSync(filename[, options])
57 fs.writeFile(filename, data[, options], callback)
异步写入文件内容。
58 fs.writeFileSync(filename, data[, options])
同步版的 fs.writeFile。
59 fs.appendFile(filename, data[, options], callback)
异步追加文件内容。
60 fs.appendFileSync(filename, data[, options])
The 同步 version of fs.appendFile.
61 fs.watchFile(filename[, options], listener)
查看文件的修改。
62 fs.unwatchFile(filename[, listener])
停止查看 filename 的修改。
63 fs.watch(filename[, options][, listener])
查看 filename 的修改,filename 可以是文件或目录。返回 fs.FSWatcher 对象。
64 fs.exists(path, callback)
检测给定的路径是否存在。
65 fs.existsSync(path)
同步版的 fs.exists.
66 fs.access(path[, mode], callback)
测试指定路径用户权限。
67 fs.accessSync(path[, mode])
同步版的 fs.access。
68 fs.createReadStream(path[, options])
返回ReadStream 对象。
69 fs.createWriteStream(path[, options])
返回 WriteStream 对象。
70 fs.symlink(srcpath, dstpath[, type], callback)
异步 symlink().回调函数没有参数,但可能抛出异常。
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# 内置模块path
# 事件
例:
var EventEmitter = require('events');
var em = new EventEmitter();
function teacher(){
console.log('老师进教室');
}
function student(){
console.log('学生进教室');
}
em.addListener('bell',teacher);
em.on('bell',);
em.emit('bell');
//on 与 addListener功能是一样的。on 是addListener的别名。
//once 是只执行一次 触发后会被移除
em.setMax
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 启动mongodb
在mac下使用步骤如下:
- 进入mongodb目录下
cd /usr/local/mongodb/bin
- 启动MongoDB,执行这一步的前提是必须有dbpath目录和log目录,且者两个目录的所有者为当前用户,否则启动后无法写入数据
./mongod --dbpath /usr/local/var/mongodb --logpath /usr/local/var/log/mongodb/mongo.log
- 启动后,还是在第一步的bin目录下执行命令
./mongo
成功进入mongoDB,就可以愉快的进行各种操作了