node.js-0030,文件读写操作

ゝ一纸荒年。 2022-05-09 07:38 337阅读 0赞

Node API文档: https://nodejs.org/dist/latest-v10.x/docs/api/fs.html#fs_fs_writefile_file_data_options_callback

1、文件写入

  1. // 导入fs模块
  2. const fs = require('fs');
  3. // 写入String
  4. var message = '第一个文件写入,hello world!';
  5. // helloworld.txt 写入的文件名称
  6. // message 写入的内容 可以是String 和buffer(byte数组)
  7. // 配置项
  8. // 回调函数
  9. fs.writeFile('helloworld.txt', message, (err)=>{
  10. // err为null表示成功
  11. if(err){
  12. console.log('文件写入失败,错误信息:' + err);
  13. } else {
  14. console.log('文件写入成功!');
  15. }
  16. })
  17. // 写入buffer
  18. const data = new Uint8Array(Buffer.from('Hello Node.js'));
  19. fs.writeFile('message.txt', data, (err) => {
  20. if (err) throw err;
  21. console.log('The file has been saved!');
  22. });

helloworld.txt

70

message.txt

70 1

2、文件读取

  1. const fs = require('fs');
  2. // helloworld.txt 被读取的文件
  3. // 配置参数,传了utf8 data默认就被转为字符,否则为字节,需要调用toString()方法
  4. // 回调函数
  5. fs.readFile('helloworld.txt', (err, data) => {
  6. if (err) throw err;
  7. console.log(data.toString());
  8. });

效果

70 2

发表评论

表情:
评论列表 (有 0 条评论,337人围观)

还没有评论,来说两句吧...

相关阅读