Node.js 中 fs 模块使用样例 -- 文件读写

本文详细介绍了Node.js中的fs模块,包括文件读写、同步复制和异步复制、大文件处理、文件上传和下载、断点续传以及isFile()函数的使用。强调了异步API的顺序控制和大文件处理时内存管理的重要性,并提供了多个代码示例。
摘要由CSDN通过智能技术生成

Node.js文件 I/O 是由简单封装的标准 POSIX 函数提供的[1]。 fs(File System)是Node.js的内置模块,可直接通过

const fs = require('fs');

使用该模块。  fs 模块所有的API都有异步和同步的形式。异步形式始终以完成回调作为它最后一个参数。 传给完成回调的参数取决于具体方法,但第一个参数总是留给异常。 如果操作成功完成,则第一个参数会是 null 或 undefined。当使用同步形式时,任何异常都会被立即抛出。 可以使用 try/catch 来处理异常,或让它们往上冒泡。使用异步API无法保证函数调用顺序. 下列代码中使用fs.rename更改一文件名称,然后使用fs.stat检验改名操作结果。如果使用异步API,fs.stat可能会在调用fs.rename前执行[1].

fs.rename('/tmp/hello', '/tmp/world', function(err){
  if (err) throw err;
  console.log('renamed complete');
});
fs.stat('/tmp/world', function(err, stats){
  if (err) throw err;
  console.log(`stats: ${JSON.stringify(stats)}`);
});

正确的做法是使用一系列回调函数来保证API调用顺序

fs.rename('/tmp/hello', '/tmp/world', function(err){
  if (err) throw err;
  fs.stat('/tmp/world', function(err, stats){
    if (err) throw err;
    console.log(`stats: ${JSON.stringify(stats)}`);
  });
});

文件读写

使用readFile读文件样例[2]

var fs = require('fs'); 

var readFileName = './foo.txt';  
var writeFileName = './target.txt';  

/** Using the readFile API - Asynchronous */
fs.readFile( readFileName, "utf8", function(err, data){
  if ( err ){ throw err;}
  console.log("Reading file asynchronously");
  console.log(data);
});

使用readFileSync读文件样例[2]

var fs = require('fs'); 

var readFileName = './foo.txt';  
var writeFileName = './target.txt';  

/** Using the readFile API - Asynchronous */
console.log("Reading file synchronously");
var fileData = fs.readFileSync(  readFileName, "utf8");
console.log(fileData);

使用ReadStream读文件样例[2]

var fs = require('fs'); 

var readFileName = './foo.txt';  
var writeFileName = './target.txt';  

/** Reading file using ReadStream API */
//Creating a stream out of the file
var readStreamObject = fs.createReadStream( readFileName, { flags: 'r',
  encoding:"utf8",
  fd: null,
  mode: 0666,
  autoClose: true
});

//Setting up event handlers on the stream object
//readable - this event is fired when data can be read from stream
readStreamObject.on('readable', function(){
  console.log("*** Reading from file using ReadStream");
});


//data - this event is fired when data is available to be read from stream
readStreamObject.on('data', function(data){
  console.log(data);
});

使用writeFileSync写文件样例[2]

var fs = require('fs'); 

var readFileName = './foo.txt';  
var writeFileName = './target.txt';  

fs.writeFileSync( writeFileName, "Writing to a file synchronously from node.js", {"encoding":'utf8'});

console.log("*** File written successfully");

//Now reading the same file to confirm data written
fs.readFile(  writeFileName, "utf8", function(err, data){
  if ( err ){ throw err;}
  console.log("*** Reading just written file");
  console.log(data);
});

使用writeFile写文件样例[2]

var fs = require('fs'); 

var readFileName = './foo.txt';  
var writeFileName = './target.txt';  

fs.writeFile(  writeFileName, "Writing to a file from node.js", {"encoding":'utf8'}, function(err){
  if ( err ) { throw err; }
  console.log("*** File written successfully");
  //Now reading the same file to confirm data written
  fs.readFile( writeFileName, "utf8", function(err, data){
    if ( err ){ throw err;}
    console.log("*** Reading just written file");
    console.log(data);
  });

});
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值