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