1. 程式人生 > >Node.js中fs檔案系統-與檔案file相關;

Node.js中fs檔案系統-與檔案file相關;

1.首先引入fs檔案模組;

//讀取檔案;

fs.readFile(path[, options], callback) 

path:檔名;

options:檔案讀取方式;

callback:回撥函式;回撥函式有兩個引數err data  其中data是檔案的內容;

var fs = require("fs");
//讀取檔案;
fs.readFile("./memeda/mamada.txt",function(err,data){
    console.log(err);
    console.log(data.toString())//得到檔案內容;
})

//將內容寫入檔案;

fs.writeFile(file, data[, options], callback)

file:要寫入的檔案的名字;

data:即將寫入檔案的內容;

callback:回撥函式;

var fs = require("fs");
//讀取檔案;
var str = "fdsahfjhajkdsf";
//如果沒有檔案,就會建立一個檔案;
fs.writeFile("./xieru",str,function(err){
    console.log(err)
})

非同步追加資料到檔案:

將內容追加到檔案的後面;

fs.appendFile(

file, data[, options], callback);

file:追加資料的檔名;

data:追加的內容;

callback:回撥函式;

fs.appendFile("./xieru.txt",Buffer.from("----我是追加的"),function(err){
    console.log(err);
})

刪除檔案:

fs.unlink(path,callback);

fs.unlink("./xieru.txt",function(err){
    console.log(err)
})