exports 与 module.exports readFile 与 writeFile path

本文详细介绍了Node.js中模块的导出与引入方式,包括使用exports和module.exports的区别,以及如何通过fs模块进行文件的读写操作。同时,还讲解了path模块在路径拼接与获取当前目录路径的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值