nodejs-fs、path

本文介绍了Node.js中fs模块的基本用法,包括文件的读取、写入、删除及目录的操作等。同时展示了如何使用path模块处理不同操作系统下的路径问题。

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

path路径const path = require(‘path’);

path.basename(‘C:\\temp\\myfile.html’);

在POSIX上返回’C:\\temp\\myfile.html’,而在windows返回’myfile.html’;

要想强制返回某一个系统上的风格时:

windows : path.win32.basename(‘C:\\temp\\myfile.html’);

POSIX :path.posix.basename(‘C:\\temp\\myfile.html’);

 

fs文件系统const fs = require(‘fs’);

fs模块中所有方法都有同步和异步两种形式,同样的方法在异步方法名(fs.unlink())后面添加Sync(fs.unlinkSync())就是同步方法名,Sync表示时同步方法;异步的方法第一个参数一定是异常参数(exception),若方法正常完成,该参数为null或undefined,最后一个参数都是完成时的回调函数

   同异步切换实例

 基本方法:

读取:fs.readFile(url, (err,data)=>{})    // data是以一个Buffer流的形式读取

写入:fs.writeFile(filename, data, [option], (err)=>{})    //option默认覆盖,{'flag': 'a'}追加写入  #option.flag

删除:fs.unlink(url, (err)=>{})

 

读:

var fs = require('fs');
//*----------------------------------读取----------------------------------------------*/
// fs.readFile(filename,[option], callback) 读取文件

fs.readFile('./hello.txt',function(err,data){
    if(err){
        throw err;
    }

    // 数据在缓冲区中的二进制内容
    console.log(data);  // 输出结果:<Buffer 6c 69 6e 65 20 6f 6e 65 0d 0a 6c 69 6e 65 20 74 77 6f>
    // 使用toString()方法转化
    console.log(data.toString());
});
//或者设置输出编码格式
console.log('为readFile设置输出编码格式');
fs.readFile('./hello.txt','utf-8' , function(err,data){
    if(err){
        throw err;
    }
    console.log(data);
});

 写:

//----------------------------------写入----------------------------------------------
// fs.writeFile(filename, data, [option], callback) !!! 覆盖式!!!
// 传递追加参数{ 'flag': 'a' }

fs.writeFile('./hello.txt', '\nline three',{'flag': 'a'}, function(err){
    if(err){
        throw err;
    }

    // 同步方法读取文件
    console.log(fs.readFileSync('./hello.txt', 'utf-8'));
})

//写入不存在的文件时:文件不存在,创建一个该文件,然后写入

直接写入到不存在的文件???
fs.writeFile('./create.txt', 'How do you do?', function(err){
   if(err){
       throw err;
   }
   console.log('write is ok');
})

操作目录,操作文件

创建目录:fs.mkdir(url, (err)=>{});

读取目录:fs.readdir(url, (err, files)=>{});    // files的数据格式 Array

fs.readdir('./newdir',function(err,files){
    if(err){throw err}
    console.log(files);    // Array
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值