node.js系统模块

系统模块

1.什么是系统模块

node运行环境提供的API

2.系统模块fs文件操作

1.读取文件内容readFile()方法

// 1.通过模块的名字fs对模块进行引用
1.const fs = require('fs');

// 2.通过模块内部的readFile读取文件内容
fs.readFile('./01.helloworld.js', 'utf8', (err, doc) => {
	// 如果文件读取出错err 是一个对象 包含错误信息
	// 如果文件读取正确 err是 null
	// doc 是文件读取的结果
	console.log(err);
	console.log(doc);
});

2.写入文件内容 writeFile()方法

const fs = require('fs');

fs.writeFile('./demo.txt', '即将要写入的内容', err => {
	if (err != null) {
		console.log(err);
		return;
	}

	console.log('文件内容写入成功');
})

3.路径拼接语法 join()方法

// public/uploads/avatar
const path = require('path');

const finalPath = path.join('public', 'uploads','avatar');

console.log(finalPath); //public\uploads\avatar

4.相对路径和绝对路径
大部分情况使用相对路径,在读取文件或设置文件路径是使用绝对路径
使用__dirname获取当前文件所在位置的绝对路径

const fs = require('fs');
const path = require('path');

console.log(__dirname); //D:\code\node\node.js day01
console.log(path.join(__dirname, '01.helloworld.js')) //D:\code\node\node.js day01\01.helloworld.js

fs.readFile(path.join(__dirname, '01.helloworld.js'), 'utf8', (err, doc) => {
	console.log(err) //null
	console.log(doc) //整个01.helloworld.js内容
});
posted @ 2020-11-06 21:50  BesePawn  阅读(81)  评论(0编辑  收藏  举报