使用NodeJS模块-NodeJS官方提供的核心模块

  • 除了使用自己写的本地模块以外,NodeJS可以使用另外两种类型的模块,分别是NodeJS官方提供的核心模块第三方提供的模块

 

NodeJS官方提供的核心模块

 

NodeJS平台自带的一套基本的功能模块,也被称为NodeJS平台的API

 

// 使用模块全局的 require() 方法引入 fs 模块
const fs = require('fs')

// 使用 fs 模块导出的 readFile() 方法读取 data.json 文件中的内容
fs.readFile('./data.json', {encoding: 'utf8', flag: 'r'}, (err, data) => {})
  • .readFire( )方法读取 data.json 文件中的内容, 
  •   './data.json' 是要读取的文件,
  • encoding: 'utf8',是字符编码,
  • flag: 'r',是读取的方式,
  •  读取成功时,err 为 null,data 为读取到的数据
     读取失败时,err 为错误对象,data 为 undefined
  • (err, data),err是检查文件是否存在,如果不存在打印undifined,并终止进程运行,
  • data是文件存在并继续访问的数据,

 

使用fs.writeFile()方法给data文件里传数据(‘写’文件要在‘读’文件里追加)
 1 const fs = require('fs');
 2 
 3 fs.readFile('data.json', { encoding: 'utf8', flag: 'r' }, (err, data) => {
 4 
 5     // 给data文件里传值
 6 
 7     // 将json格式的字符串转换成js对象(array,object)
 8     data = JSON.parse(data)
 9     console.log(typeof data);  //string
10     console.log(data instanceof Array)  //true
11     //   写内容
12     const student = {
13         fullNmae: 'zzj',
14         age: 18,
15         hobby: '学习',
16         gender: '女'
17     }
18     // 向data里面追加student
19     data.push(student);
20     // 将js对象转换成json对象
21      JSON.stringify(data)
22     // 使用fs.writeFile()方法给data文件里传数据
23     fs.writeFile('data.json',JSON.stringify(data ,null,4), (err) => {
24         if (err) {
25             console.log('失败')
26             return;
27         }
28         console.log('成功')
29     })
30 })
JSON.stringify(data ,null,4)  
null:表示函数,不需要函数则写null,
4:表示4个字符间距(效果如下图)


 

os操作系统

1 const os = require('os')
2 console.log(os.freemem()/1024/1024/1024)
3 // 获取家目录
4 console.log(os.homedir())
5 // 获取CPU架构
6 console.log(os.arch())
7 // 获取几核
8 console.log(os.cpus())       

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2019-12-16 21:02  张尊娟  阅读(430)  评论(0编辑  收藏  举报