exports
暴露出方法让想调用的人require
const add = (n1, n2) => n1 + n2;
exports.add = add;
const a = require('绝对路径');
console.log(a.add(10, 20));
module.exports
const greeting = name => `hello ${name}`;
const x = 100;
exports.x = x;
module.exports.greeting = greeting;
// 当exports对象和moudle.exports对象指向的不是同一个对象时 以module.exports为准
module.exports = {
name: 'zhangsan'
}
exports = {
age: 20
}
// 调用
const a = require('./04.module.exports.js');
// console.log(a.greeting('zhangsan'));
console.log(a);
readFile 与 writeFile
通过模块的名字fs对模块进行引用
const fs = require(‘fs’);
1.通过模块内部的readFile读取文件内容
fs.readFile(’./01.helloworld.js’, ‘utf8’, (err, doc) => {
// 如果文件读取出错err 是一个对象 包含错误信息
// 如果文件读取正确 err是 null
// doc 是文件读取的结果
console.log(err);
console.log(doc);
});
2如果该文件会创建后写入
.fs.writeFile(’./demo.txt’, ‘即将要写入的内容’, err => {
if (err != null) {
console.log(err);
return;
}
path 路径拼接 与获取当前文件夹路径__dirname
const path = require(‘path’);
const finalPath = path.join(‘public’, ‘uploads’,‘avatar’);
console.log(finalPath);