一、基础定义
Node.js是运行在服务区端的JavaScript环境,服务器程序和浏览器程序对比,没有浏览器的安全限制,服务程序必须接收网络请求,读写文件,处理二进制内容。nodejs模块实现了基本的服务器功能,这些模块在浏览器是没法执行的,底层是使用了c/c++在Node.js运行环境中实现的。
二、模块分类
global:js中有且仅有一个全局对象,在浏览器中是window。在node.js中的全局对象则是global,这个对象的属性和方法也和浏览器环境中的window不同。我们从黑窗口进入可以看到
C:\Users\Administrator>node
Welcome to Node.js v12.16.3.
Type ".help" for more information.
> global.console
{
log: [Function: bound consoleCall],
warn: [Function: bound consoleCall],
dir: [Function: bound consoleCall],
time: [Function: bound consoleCall],
timeEnd: [Function: bound consoleCall],
timeLog: [Function: bound consoleCall],
trace: [Function: bound consoleCall],
assert: [Function: bound consoleCall],
clear: [Function: bound consoleCall],
count: [Function: bound consoleCall],
countReset: [Function: bound consoleCall],
group: [Function: bound consoleCall],
groupEnd: [Function: bound consoleCall],
table: [Function: bound consoleCall],
debug: [Function: bound consoleCall],
info: [Function: bound consoleCall],
dirxml: [Function: bound consoleCall],
error: [Function: bound consoleCall],
groupCollapsed: [Function: bound consoleCall],
Console: [Function: Console],
profile: [Function: profile],
profileEnd: [Function: profileEnd],
timeStamp: [Function: timeStamp],
context: [Function: context],
[Symbol(kBindStreamsEager)]: [Function: bound ],
[Symbol(kBindStreamsLazy)]: [Function: bound ],
[Symbol(kBindProperties)]: [Function: bound ],
[Symbol(kWriteToConsole)]: [Function: bound ],
[Symbol(kGetInspectOptions)]: [Function: bound ],
[Symbol(kFormatForStdout)]: [Function: bound ],
[Symbol(kFormatForStderr)]: [Function: bound ]
process:node提供的一个对象,代表当前的Node.js进程
> process ===global.process
true
> process.version
'v12.16.3'
> process.platform
'win32'
> process.arch
'x64'
> process.cmd()
Uncaught TypeError: process.cmd is not a functi
> process.cwd()
'C:\\Users\\Administrator'
>
JavaScript程序是由事件驱动执行的单线程模型,Node.js也是。
fs模块:文件系统模块,负责读写文件。fs模块提供了异步和同步的方法。
a.异步方法:执行IO操作的时候,js代码无需等待,传入回调函数后,继续执行js代码。
b.同步方法:执行IO操作的时候,js代码需等待,传入回调函数后,返回,继续执行js代码。
同步操作的好处是代码简单,缺点是程序将等待IO操作,在等待时间内,无法响应其它任何事件。而异步读取不用等待IO操作,但代码较麻烦。
读入文件,创建一个demoone.js文件,然后在同级目录下创建a.txt文件
demoone.js文件
'use strict'; //严格模式下执行
var fs = require('fs'); //引入fs模块
fs.readFile('a.txt', 'utf-8', function (err, data) { //读入文件 进行判断
if (err) {
console.log(err);
} else {
console.log(data);
}
});
运行js,注意配置:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "main",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\main.js"
},
{
"type": "node",
"request": "launch",
"name": "demoone",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\demoone.js"
}
]
}
注意修改name,否则运行只会出现第一个js文件的结果。
从上面的例子可以看出我们在异步调用的时候传入的是两个参数,分别是err和data,err为null时,data为读取到的String。读取出现错误的时候err读取到的是一个错误对象,data为undefined。这也是Node.js标准的回调函数:第一个参数代表错误信息,第二个参数代表结果。
如果读取的是二进制文件呢(例如图片),当读取二进制文件时,不传入文件编码时,回调函数的data参数将返回一个Buffer对象。在Node.js中,Buffer对象就是一个包含零个或任意个字节的数组(注意和Array不同)。
'use strick'
var fs = require('fs')
fs.readFile('b.png',function(err,data){
if(err){
console.log(err)
}else{
console.log(data)
console.log(data.length+'byte')
}
})
D:\nodejs\node.exe --inspect-brk=24318 demotwo.js
Debugger listening on ws://127.0.0.1:24318/f55d96fb-ea99-42fc-9882-212c20e8c591
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
Buffer(0) []
demotwo.js:7
0byte
文件路径不要错哦
Buffer对象与String进项相互转换:
var s = data.toString("utf-8")//Buffer转String
var t = Buffer.from(text,'utf-8')//String转Buffer
同步方法读取文件,就是多了一个sync,有错与了进行try{}catch(erro){}
'use strick'
var fs = require('fs')
try {
var data = fs.readFileSync('a.txt','utf-8')
console.log(data)
} catch (error) {
console.log(error)
}
c.写文件:默认同级目录下,不用提前创建。与之对应的还有
'use strick';
var fs = require('fs')
var hello = 'hello world';
fs.writeFile('out.txt',hello,function(err){
if(err){
console.log(err)
}else{
console.log('ok')
}
});
还有同步的fs.writeFileSync()同步方法。writeFile()的参数依次为文件名、数据和回调函数。如果传入的数据是String,默认按UTF-8编码写入文本文件,如果传入的参数是Buffer,则写入的是二进制文件。回调函数由于只关心成功与否,因此只需要一个err参数。
stat:可以获取文件信息。例如获取读取文件的大小,创建时间的。
'use strick';
var fs = require('fs');
fs.stat('a.txt',function(err,data){
if(err){
console.log(err);
}else{
console.log('a.txt is a file' +data.isFile());
console.log('a.txt is a directory'+data.isDirectory());
if(data.isFile()){
console.log(data.size);
console.log(data.birthtime);
console.log(data.mtime);
}
}
})
运行结果:
D:\nodejs\node.exe --inspect-brk=46748 fsstat.js
Debugger listening on ws://127.0.0.1:46748/03a61bab-60e2-44ee-8b64-1eea9b65886a
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
a.txt is a filetrue
fsstat.js:7
a.txt is a directoryfalse
fsstat.js:8
26
fsstat.js:10
Sun Jun 07 2020 17:41:39 GMT+0800 (GMT+08:00) {}
fsstat.js:11
Sun Jun 07 2020 18:09:37 GMT+0800 (GMT+08:00) {}
总结:
a.在fs模块中提供了同步和异步的方法,由于node执行的js代码是服务端代码,需要在服务端反复执行,所以必须使用异步代码。同步执行的话,服务器将停止响应,js是单线程。
b.服务器启动时如果需要读取配置文件,或者结束时需要写入到状态文件时,可以使用同步代码,因为这些代码只在启动和结束时执行一次,不影响服务器正常运行时的异步执行。