node 写入文件内容


  1.   在Node.js中写入文件的最简单方法是使用 fs.writeFile()
       const fs=require('fs');
       const content = 'this is the content';
       fs.writeFile('./jiyu.txt',content,(err)=>{
           if(err) {
                 console.error(err);
                 return
           }
      });
 
      运行结果:
    jiyu.txt 原内容是         这是node读出来的内容      
    运行完毕是      this is the content    
 
   2. 另外,您可以使用同步版本fs.writeFileSync()
    const fs= require('fs');
    const content = 'Some content';
    try {
           fs.writeFileSync('./jiyu.txt',content);
       }catch(err){
           console.log(err);
    }
 
   运行结果:
   jiyu.txt 原内容是    this is the content  
   运行完毕是     Some content 
 
3.
    const fs = require('fs');
    const replace_content = 'repace old content';
// fs.writeFile('./jiyu.txt',replace_content,{flag:'r+'},(err)=>{});
    fs.writeFile('./jiyu.txt',replace_content,{flag:'w+'},(err)=>{});
 
  运行结果:
     jiyu.txt 原内容是     this is the content  
     运行完毕是      Some content 
 
4.
    
    const fs = require('fs');
    const append_content = 'append new content';
// fs.writeFile('./jiyu.txt',append_content,{flag:'a+'},(err)=>{});
    fs.appendFile('./jiyu.txt',append_content,(err)=>{
    if(err){
           console.error(err);
           return
    }
    });
  运行结果:
     jiyu.txt 原内容是     Some content 
     运行完毕是     Some contentappend new content'
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM