Skip to content

REPL (interactive interpreter) ​

Node.js REPL (Read Eval Print Loop: interactive interpreter) represents a computer environment, similar to the terminal of the Window system or the Unix/Linux shell. We can enter commands in the terminal and receive the system's response. Node comes with an interactive interpreter that can perform the following tasks:

  • Read - Reads user input, parses the input Javascript data structure and stores it in memory.
  • Execute - Execute the input data structure
  • Print - Output the results
  • Loop - Loop through the above steps until the user presses the ctrl-c button twice to exit.

Node's interactive interpreter is great for debugging Javascript code. Start learning REPL We can enter the following command to start Node’s terminal:

$ node
>

At this time we can enter a simple expression after > and press the Enter key to calculate the result.

Simple expression operations ​

Next let's perform simple math operations in the command line window of the Node.js REPL:

$ node
> 1 +4
5
> 5 / 2
2.5
> 3 * 6
18
> 4 - 1
3
> 1 + ( 2 * 3 ) - 4
3
>
use variables ​

You can store data in variables and use it when you need it. Variable declaration requires the use of the var keyword. If the var keyword is not used, the variable will be printed directly. Variables using the var keyword can use console.log() to output the variable.

$ 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
multiline expression ​

Node REPL supports entering multi-line expressions, which is somewhat similar to JavaScript.Next let's execute a do-while loop:

$ 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
>

... The three-dot symbol is automatically generated by the system, just press Enter and line feed.Node will automatically detect whether it is a continuous expression.

Underscore (_) variable ​

You can use the underscore (_) to get the result of the previous expression:

$ node
> var x = 10
undefined
> var y = 20
undefined
> x + y
30
> var sum = _
undefined
> console.log(sum)
30
undefined
>
REPL command ​

ctrl + c - Exit the current terminal. ctrl + c pressed twice - Exit Node REPL. ctrl + d - Exit Node REPL. Up/Down keys - view the history of entered commands tab key - list current commands .help - lists commands to use .break - break out of a multiline expression .clear - exit a multiline expression .save filename - Save the current Node REPL session to the specified file .load filename - Load the file contents of the current Node REPL session.

console ​

How to save logs

node x.console.log.js > 1.log

node app 1>app.log 2>&1 or 1>app.log 2>app.err

Log redirection

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

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
>
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 - 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.

Reference website

// 一:页面代码
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);
//输出结果:

Buffer ​

The JavaScript language itself only has string data types, not binary data types. But when dealing with streams like TCP or file streams, binary data must be used.Therefore, in Node.js, a Buffer class is defined, which is used to create a buffer area specifically for storing binary data. In Node.js, the Buffer class is a core library shipped with the Node core.The Buffer library brings a way to store raw data to Node.js, allowing Node.js to process binary data. Whenever you need to handle data moved in I/O operations in Node.js, it is possible to use the Buffer library.Raw data is stored in instances of the Buffer class.A Buffer is similar to an integer array, but it corresponds to a piece of raw memory outside of the V8 heap memory.

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()

Create Buffer class ​

  • Buffer provides the following APIs to create Buffer classes:
  • Buffer.alloc(size[, fill[, encoding]]): Returns a Buffer instance of the specified size. If fill is not set, it will be filled with 0 by default.
  • Buffer.allocUnsafe(size): Returns a Buffer instance of the specified size, but it will not be initialized, so it may contain sensitive data
  • Buffer.allocUnsafeSlow(size)
  • Buffer.from(array): Returns a new Buffer instance initialized by the value of array (the elements of the passed array can only be numbers, otherwise they will be automatically overwritten by 0)
  • Buffer.from(arrayBuffer[, byteOffset[, length]]): Returns a new Buffer that shares the same memory as the given ArrayBuffer.
  • Buffer.from(buffer): Copies the data of the passed Buffer instance and returns a new Buffer instance
  • Buffer.from(string[, encoding]): Returns a new Buffer instance initialized by the value of string

Character encodings currently supported by Node.js include:

  • ascii - Only 7-bit ASCII data is supported.This encoding is very fast if the high bits are removed.
  • utf8 - Multibyte encoded Unicode characters.Many web pages and other document formats use UTF-8.
  • utf16le - 2 or 4-byte, little-endian encoded Unicode character.Supports surrogate pairs (U+10000 to U+10FFFF).
  • ucs2 - Alias for utf16le.
  • base64 - Base64 encoding.
  • latin1 - A way to encode a Buffer into a one-byte encoded string.
  • binary - Alias for latin1.
  • hex - Encodes each byte into two hexadecimal characters.
write buffer ​
  • Grammar

The syntax for writing to a Node buffer is as follows: buf.write(string[, offset[, length]][, encoding])

parameters ​

The parameters are described as follows:

  • string - the string to write to the buffer.
  • offset - the index value at which buffer writing begins, default is 0 .
  • length - the number of bytes written, defaults to buffer.length
  • encoding - the encoding to use.Defaults to 'utf8' .

Writes a string to the offset position in buf according to the character encoding of encoding.The length parameter is the number of bytes written.If buf does not have enough space to hold the entire string, only a portion of string will be written.Characters that are only partially decoded are not written.

return value ​

Returns the actual size written.If there is insufficient buffer space, only part of the string will be written.

buf = Buffer.alloc(256);
len = buf.write("www.runoob.com");

console.log("写入字节数 : "+  len);
Read data from buffer ​
Grammar ​

The syntax for reading Node buffer data is as follows: buf.toString([encoding[, start[, end]]])

parameters ​

The parameters are described as follows:

  • encoding - the encoding to use.Defaults to 'utf8' .
  • start - specifies the index position to start reading, default is 0.
  • end - the end position, defaults to the end of the buffer.
return value ​

Decodes the buffer data and returns a string using the specified encoding.

Reference document Node.js Buffer (buffer)

Modules and packages ​

When the code is run it will become

function(exports,require,module,__filename,__dirname){
var sum = function(a,b){
return a + b;
}
exports.sum = sum;
return module.exports;
}

//exports default export object //require is a method to load other modules //module represents the current module object module.exports //__filename is the absolute path of the current module //_dirname is the absolute directory of the current module

code block reference

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);

Built-in module ​

There are many built-in modules, refer to the v8 documentation for details

Built-in module fs ​

File module methods reference manual ​
序号	方法 & 描述
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().回调函数没有参数,但可能抛出异常。

Reference Document

Built-in module path ​

Reference Document

event ​

Example:

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

Start mongodb ​

The steps to use under mac are as follows:

  1. Enter the mongodb directory
 cd /usr/local/mongodb/bin
  1. Start MongoDB. The prerequisite for this step is that there must be a dbpath directory and a log directory, and the owner of the two directories is the current user. Otherwise, data cannot be written after startup.
./mongod --dbpath /usr/local/var/mongodb --logpath /usr/local/var/log/mongodb/mongo.log
  1. After startup, still execute the command in the bin directory in the first step
./mongo

After successfully entering mongoDB, you can happily perform various operations.

Reference Document