Node.js文件操作方法匯總
來(lái)源:易賢網(wǎng) 閱讀:712 次 日期:2016-07-19 14:14:17
溫馨提示:易賢網(wǎng)小編為您整理了“Node.js文件操作方法匯總”,方便廣大網(wǎng)友查閱!

Node.js和其他語(yǔ)言一樣,也有文件操作。先不說(shuō)node.js中的文件操作,其他語(yǔ)言的文件操作一般也都是有打開(kāi)、關(guān)閉、讀、寫(xiě)、文件信息、新建刪除目錄、刪除文件、檢測(cè)文件路徑等。在node.js中也是一樣,也都是這些功能,可能就是api與其他語(yǔ)言不太一樣。

一、同步、異步打開(kāi)關(guān)閉

/**

 * Created by Administrator on 2016/3/21.

 */

var fs=require("fs");

//同步讀 fs.openSync = function(path, flags, mode)

//模塊fs.js文件中如上面定義的openSync 函數(shù)3個(gè)參數(shù)

//.1.path 文件路徑

//2.flags 打開(kāi)文件的模式

//3.model 設(shè)置文件訪問(wèn)模式

//fd文件描述

var fd=fs.openSync("data/openClose.txt",'w');

//fs.closeSync = function(fd)

fs.closeSync(fd);

//異步讀寫(xiě)

//fs.open = function(path, flags, mode, callback_)

//fs.close = function(fd, callback)

fs.open("data/openColse1.txt",'w',function(err,fd) {

  if (!err)

  {

    fs.close(fd,function(){

      console.log("closed");

    });

  }

});

其中的flags其他語(yǔ)言也會(huì)有.其實(shí)主要分3部分 r、w、a.和C中的差不多。

1.r —— 以只讀方式打開(kāi)文件,數(shù)據(jù)流的初始位置在文件開(kāi)始

2.r+ —— 以可讀寫(xiě)方式打開(kāi)文件,數(shù)據(jù)流的初始位置在文件開(kāi)始

3.w ——如果文件存在,則將文件長(zhǎng)度清0,即該文件內(nèi)容會(huì)丟失。如果不存在,則嘗試創(chuàng)建它。數(shù)據(jù)流的初始位置在文件開(kāi)始

4.w+ —— 以可讀寫(xiě)方式打開(kāi)文件,如果文件不存在,則嘗試創(chuàng)建它,如果文件存在,則將文件長(zhǎng)度清0,即該文件內(nèi)容會(huì)丟失。數(shù)據(jù)流的初始位置在文件開(kāi)始

5.a —— 以只寫(xiě)方式打開(kāi)文件,如果文件不存在,則嘗試創(chuàng)建它,數(shù)據(jù)流的初始位置在文件末尾,隨后的每次寫(xiě)操作都會(huì)將數(shù)據(jù)追加到文件后面。

6.a+ ——以可讀寫(xiě)方式打開(kāi)文件,如果文件不存在,則嘗試創(chuàng)建它,數(shù)據(jù)流的初始位置在文件末尾,隨后的每次寫(xiě)操作都會(huì)將數(shù)據(jù)追加到文件后面。

二、讀寫(xiě)

1.簡(jiǎn)單文件讀寫(xiě)

/**

 * Created by Administrator on 2016/3/21.

 */

var fs = require('fs');

var config = {

  maxFiles: 20,

  maxConnections: 15,

  rootPath: "/webroot"

};

var configTxt = JSON.stringify(config);

var options = {encoding:'utf8', flag:'w'};

//options 定義字符串編碼 打開(kāi)文件使用的模式 標(biāo)志的encoding、mode、flag屬性 可選

//異步

//fs.writeFile = function(path, data, options, callback_)

//同步

//fs.writeFileSync = function(path, data, options)

fs.writeFile('data/config.txt', configTxt, options, function(err){

  if (err){

    console.log("Config Write Failed.");

  } else {

    console.log("Config Saved.");

    readFile();

  }

});

function readFile()

{

  var fs = require('fs');

  var options = {encoding:'utf8', flag:'r'};

  //異步

  //fs.readFile = function(path, options, callback_)

  //同步

  //fs.readFileSync = function(path, options)

  fs.readFile('data/config.txt', options, function(err, data){

    if (err){

      console.log("Failed to open Config File.");

    } else {

      console.log("Config Loaded.");

      var config = JSON.parse(data);

      console.log("Max Files: " + config.maxFiles);

      console.log("Max Connections: " + config.maxConnections);

      console.log("Root Path: " + config.rootPath);

    }

  });

}

-------------------------------------------------

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe SimpleReadWrite.js

Config Saved.

Config Loaded.

Max Files: 20

Max Connections: 15

Root Path: /webroot

Process finished with exit code 0

2.同步讀寫(xiě)

/**

 * Created by Administrator on 2016/3/21.

 */

var fs = require('fs');

var veggieTray = ['carrots', 'celery', 'olives'];

fd = fs.openSync('data/veggie.txt', 'w');

while (veggieTray.length){

  veggie = veggieTray.pop() + " ";

  //系統(tǒng)api 

  //fd 文件描述 第二個(gè)參數(shù)是被寫(xiě)入的String或Buffer

  // offset是第二個(gè)參數(shù)開(kāi)始讀的索引 null是表示當(dāng)前索引

  //length 寫(xiě)入的字節(jié)數(shù) null一直寫(xiě)到數(shù)據(jù)緩沖區(qū)末尾

  //position 指定在文件中開(kāi)始寫(xiě)入的位置 null 文件當(dāng)前位置

  // fs.writeSync(fd, buffer, offset, length[, position]);

  // fs.writeSync(fd, string[, position[, encoding]]);

  //fs.writeSync = function(fd, buffer, offset, length, position)

  var bytes = fs.writeSync(fd, veggie, null, null);

  console.log("Wrote %s %dbytes", veggie, bytes);

}

fs.closeSync(fd);

var fs = require('fs');

fd = fs.openSync('data/veggie.txt', 'r');

var veggies = "";

do {

  var buf = new Buffer(5);

  buf.fill();

  //fs.readSync = function(fd, buffer, offset, length, position)

  var bytes = fs.readSync(fd, buf, null, 5);

  console.log("read %dbytes", bytes);

  veggies += buf.toString();

} while (bytes > 0);

fs.closeSync(fd);

console.log("Veggies: " + veggies);

--------------------------------------------

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe syncReadWrite.js

Wrote olives 7bytes

Wrote celery 7bytes

Wrote carrots 8bytes

read 5bytes

read 5bytes

read 5bytes

read 5bytes

read 2bytes

read 0bytes

Veggies: olives celery carrots     

Process finished with exit code 0

3.異步讀寫(xiě) 和同步讀寫(xiě)的參數(shù)差不多就是多了callback

/**

 * Created by Administrator on 2016/3/21.

 */

var fs = require('fs');

var fruitBowl = ['apple', 'orange', 'banana', 'grapes'];

function writeFruit(fd){

  if (fruitBowl.length){

    var fruit = fruitBowl.pop() + " ";

   // fs.write(fd, buffer, offset, length[, position], callback);

   // fs.write(fd, string[, position[, encoding]], callback);

   // fs.write = function(fd, buffer, offset, length, position, callback)

    fs.write(fd, fruit, null, null, function(err, bytes){

      if (err){

        console.log("File Write Failed.");

      } else {

        console.log("Wrote: %s %dbytes", fruit, bytes);

        writeFruit(fd);

      }

    });

  } else {

    fs.close(fd);

    ayncRead();

  }

}

fs.open('data/fruit.txt', 'w', function(err, fd){

  writeFruit(fd);

});

function ayncRead()

{

  var fs = require('fs');

  function readFruit(fd, fruits){

    var buf = new Buffer(5);

    buf.fill();

    //fs.read = function(fd, buffer, offset, length, position, callback)

    fs.read(fd, buf, 0, 5, null, function(err, bytes, data){

      if ( bytes > 0) {

        console.log("read %dbytes", bytes);

        fruits += data;

        readFruit(fd, fruits);

      } else {

        fs.close(fd);

        console.log ("Fruits: %s", fruits);

      }

    });

  }

  fs.open('data/fruit.txt', 'r', function(err, fd){

    readFruit(fd, "");

  });

}

---------------------------------------------

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe asyncReadWrite.js

Wrote: grapes 7bytes

Wrote: banana 7bytes

Wrote: orange 7bytes

Wrote: apple 6bytes

read 5bytes

read 5bytes

read 5bytes

read 5bytes

read 5bytes

read 2bytes

Fruits: grapes banana orange apple  

Process finished with exit code 0

4.流式讀寫(xiě)

/**

 * Created by Administrator on 2016/3/21.

 */

var fs = require('fs');

var grains = ['wheat', 'rice', 'oats'];

var options = { encoding: 'utf8', flag: 'w' };

//從下面的系統(tǒng)api可以看到 createWriteStream 就是創(chuàng)建了一個(gè)writable流

//fs.createWriteStream = function(path, options) {

//  return new WriteStream(path, options);

//};

//

//util.inherits(WriteStream, Writable);

//fs.WriteStream = WriteStream;

//function WriteStream(path, options)

var fileWriteStream = fs.createWriteStream("data/grains.txt", options);

fileWriteStream.on("close", function(){

  console.log("File Closed.");

  //流式讀

  streamRead();

});

while (grains.length){

  var data = grains.pop() + " ";

  fileWriteStream.write(data);

  console.log("Wrote: %s", data);

}

fileWriteStream.end();

//流式讀

function streamRead()

{

  var fs = require('fs');

  var options = { encoding: 'utf8', flag: 'r' };

  //fs.createReadStream = function(path, options) {

  //  return new ReadStream(path, options);

  //};

  //

  //util.inherits(ReadStream, Readable);

  //fs.ReadStream = ReadStream;

  //

  //function ReadStream(path, options)

  //createReadStream 就是創(chuàng)建了一個(gè)readable流

  var fileReadStream = fs.createReadStream("data/grains.txt", options);

  fileReadStream.on('data', function(chunk) {

    console.log('Grains: %s', chunk);

    console.log('Read %d bytes of data.', chunk.length);

  });

  fileReadStream.on("close", function(){

    console.log("File Closed.");

  });

}

--------------------------------------------

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe StreamReadWrite.js

Wrote: oats 

Wrote: rice 

Wrote: wheat 

File Closed.

Grains: oats rice wheat 

Read 16 bytes of data.

File Closed.

Process finished with exit code 0

個(gè)人覺(jué)得像這些api用一用感受一下就ok了,遇到了會(huì)用就行了。

更多信息請(qǐng)查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:Node.js文件操作方法匯總
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢(xún)回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門(mén)公布的正式信息和咨詢(xún)?yōu)闇?zhǔn)!

2025國(guó)考·省考課程試聽(tīng)報(bào)名

  • 報(bào)班類(lèi)型
  • 姓名
  • 手機(jī)號(hào)
  • 驗(yàn)證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢(xún) | 簡(jiǎn)要咨詢(xún)須知 | 新媒體/短視頻平臺(tái) | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專(zhuān)用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢(xún)關(guān)注公眾號(hào):hfpxwx
咨詢(xún)QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專(zhuān)用圖標(biāo)