nodejs中有哪些读取和写文件的函数和例子

在Node.js中,我们通常使用内置的fs(文件系统)模块来读取和写入文件。以下是一些常用的函数和例子:

1. 读取文件

fs.readFile(path[, options], callback): 异步读取文件的全部内容。

fs.readFileSync(path[, options]): 同步读取文件的全部内容。

const fs = require('fs');

// 异步读取

fs.readFile('example.txt', 'utf8', (err, data) => {

  if (err) throw err;

  console.log(data);

});

// 同步读取

try {

  const data = fs.readFileSync('example.txt', 'utf8');

  console.log(data);

} catch (err) {

  console.error(err);

}

 

2. 写入文件

fs.writeFile(file, data[, options], callback): 异步写入文件,如果文件已存在,则覆盖文件。

fs.writeFileSync(file, data[, options]): 同步写入文件,如果文件已存在,则覆盖文件。

fs.appendFile(file, data[, options], callback): 异步追加内容到文件末尾。

fs.appendFileSync(file, data[, options]): 同步追加内容到文件末尾。

const fs = require('fs');

// 异步写入

const data = 'Hello, world!';

fs.writeFile('output.txt', data, (err) => {

  if (err) throw err;

  console.log('File has been saved!');

});

// 同步写入

try {

  fs.writeFileSync('output.txt', 'Hello again!');

  console.log('File has been saved!');

} catch (err) {

  console.error(err);

}

// 异步追加

fs.appendFile('output.txt', '\nThis is appended text.', (err) => {

  if (err) throw err;

  console.log('Text has been appended!');

});

// 同步追加

try {

  fs.appendFileSync('output.txt', '\nThis is more appended text.');

  console.log('More text has been appended!');

} catch (err) {

  console.error(err);

}

注意:在使用fs模块时,要确保文件路径是正确的,否则可能会导致错误。同时,对于大型文件,建议使用流(stream)来处理,以提高性能和效率。

 

 

相关推荐

  1. nodejs哪些读取文件函数例子

    2024-02-01 14:50:02       34 阅读
  2. Python文件读取方法:read、readlinereadlines

    2024-02-01 14:50:02       31 阅读
  3. Windows.h函数哪些

    2024-02-01 14:50:02       45 阅读
  4. MySQLUNIONUNION ALL区别哪些

    2024-02-01 14:50:02       38 阅读
  5. Python,如何读取写入文件

    2024-02-01 14:50:02       20 阅读
  6. MATLAB脚本函数什么区别?

    2024-02-01 14:50:02       21 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-01 14:50:02       14 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-01 14:50:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-01 14:50:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-01 14:50:02       18 阅读

热门阅读

  1. 第五章 类的继承与派生之——类的继承与派生

    2024-02-01 14:50:02       26 阅读
  2. BeanUtil.copyProperties(source,target)拷贝List注意事项

    2024-02-01 14:50:02       37 阅读
  3. 深度学习的进展

    2024-02-01 14:50:02       28 阅读
  4. 代码随想录算法训练营|day22

    2024-02-01 14:50:02       33 阅读
  5. Android studio布局详解

    2024-02-01 14:50:02       34 阅读
  6. 达梦数据库存储过程

    2024-02-01 14:50:02       26 阅读
  7. vue3:中warch监听的几种写法

    2024-02-01 14:50:02       33 阅读
  8. ModuleNotFoundError: No module named ‘flask._compat‘

    2024-02-01 14:50:02       28 阅读
  9. rsync将远程文件同步到本地

    2024-02-01 14:50:02       30 阅读