最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Node.js文件操作方法匯總

 更新時間:2016年03月22日 09:50:45   投稿:hebedich  
本文給大家匯總了node.js實現(xiàn)文件操作的方法,非常的細致全面,希望大家能夠喜歡

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

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

/**
 * Created by Administrator on 2016/3/21.
 */
var fs=require("fs");
//同步讀 fs.openSync = function(path, flags, mode)
//模塊fs.js文件中如上面定義的openSync 函數(shù)3個參數(shù)
//.1.path 文件路徑
//2.flags 打開文件的模式
//3.model 設(shè)置文件訪問模式
//fd文件描述
var fd=fs.openSync("data/openClose.txt",'w');
//fs.closeSync = function(fd)
fs.closeSync(fd);

//異步讀寫
//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其他語言也會有.其實主要分3部分 r、w、a.和C中的差不多。

1.r —— 以只讀方式打開文件,數(shù)據(jù)流的初始位置在文件開始
2.r+ —— 以可讀寫方式打開文件,數(shù)據(jù)流的初始位置在文件開始
3.w ——如果文件存在,則將文件長度清0,即該文件內(nèi)容會丟失。如果不存在,則嘗試創(chuàng)建它。數(shù)據(jù)流的初始位置在文件開始
4.w+ —— 以可讀寫方式打開文件,如果文件不存在,則嘗試創(chuàng)建它,如果文件存在,則將文件長度清0,即該文件內(nèi)容會丟失。數(shù)據(jù)流的初始位置在文件開始
5.a —— 以只寫方式打開文件,如果文件不存在,則嘗試創(chuàng)建它,數(shù)據(jù)流的初始位置在文件末尾,隨后的每次寫操作都會將數(shù)據(jù)追加到文件后面。
6.a+ ——以可讀寫方式打開文件,如果文件不存在,則嘗試創(chuàng)建它,數(shù)據(jù)流的初始位置在文件末尾,隨后的每次寫操作都會將數(shù)據(jù)追加到文件后面。

二、讀寫

1.簡單文件讀寫

/**
 * 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 定義字符串編碼 打開文件使用的模式 標(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.同步讀寫

/**
 * 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 文件描述 第二個參數(shù)是被寫入的String或Buffer
  // offset是第二個參數(shù)開始讀的索引 null是表示當(dāng)前索引
  //length 寫入的字節(jié)數(shù) null一直寫到數(shù)據(jù)緩沖區(qū)末尾
  //position 指定在文件中開始寫入的位置 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.異步讀寫 和同步讀寫的參數(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.流式讀寫

/**
 * 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)建了一個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)建了一個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

 個人覺得像這些api用一用感受一下就ok了,遇到了會用就行了。

相關(guān)文章

  • 命令行批量截圖Node腳本示例代碼

    命令行批量截圖Node腳本示例代碼

    這篇文章主要給大家介紹了關(guān)于命令行批量截圖Node腳本的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-01-01
  • Linux 安裝nodejs環(huán)境及路徑配置詳細步驟

    Linux 安裝nodejs環(huán)境及路徑配置詳細步驟

    大家都知道linux安裝nodejs有兩種比較常用的方法,一種解壓即可用的方法操作比較簡便,另一種方法通過編譯來安裝,本文重點給大家講解第一種方法,感興趣的朋友跟隨小編一起看看吧
    2021-11-11
  • Node.js實現(xiàn)簡單聊天服務(wù)器

    Node.js實現(xiàn)簡單聊天服務(wù)器

    Node.js 是一個基于Chrome JavaScript運行時建立的一個平臺, 用來方便地搭建快速的,易于擴展的網(wǎng)絡(luò)應(yīng)用,今天我們來探討下,如何使用node.js實現(xiàn)簡單的聊天服務(wù)器
    2014-06-06
  • Express之托管靜態(tài)文件的方法

    Express之托管靜態(tài)文件的方法

    本篇文章主要介紹了Express之托管靜態(tài)文件的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06
  • nodejs簡單抓包工具使用詳解

    nodejs簡單抓包工具使用詳解

    這篇文章主要介紹了nodejs簡單抓包工具使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • Express框架搭建項目的實現(xiàn)步驟

    Express框架搭建項目的實現(xiàn)步驟

    Express是一個基于Node.js平臺的輕量級Web應(yīng)用框架,它提供了簡潔的API和豐富的功能,本文主要介紹了Express框架搭建項目的實現(xiàn)步驟,感興趣的可以了解一下
    2024-06-06
  • Node.js 的 GC 機制詳解

    Node.js 的 GC 機制詳解

    隨著 Node 的發(fā)展,JavaScript 的應(yīng)用場景早已不再局限在瀏覽器中。但隨著 Node 在服務(wù)端的廣泛應(yīng)用,JavaScript 的內(nèi)存管理需要引起我們的重視。下面我們來一起學(xué)習(xí)一下吧
    2019-06-06
  • Node.js實現(xiàn)兼容IE789的文件上傳進度條

    Node.js實現(xiàn)兼容IE789的文件上傳進度條

    這篇文章給大家介紹了如何實現(xiàn)兼容IE789的文件上傳進度條,如果你的工作用過上傳圖片或上傳大文件啥的,一般在IE低版本瀏覽器里,會切換到用flash解決,可是有些人肯定不會為了老舊IE的進度條而去學(xué)flash,那么下面來一起看看吧。
    2016-09-09
  • Node.js+Express+MySql實現(xiàn)用戶登錄注冊功能

    Node.js+Express+MySql實現(xiàn)用戶登錄注冊功能

    這篇文章主要為大家詳細介紹了Node.js+Express+MySql實現(xiàn)用戶登錄注冊,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • Node.js中Swagger的使用指南詳解

    Node.js中Swagger的使用指南詳解

    Swagger(目前用OpenAPI?Specification代替)是一個用于設(shè)計、構(gòu)建、記錄和使用REST?API的強大工具,本文將探討使用Swagger的一些關(guān)鍵技巧,需要的可以參考一下
    2024-01-01

最新評論

沙河市| 朝阳区| 江北区| 普格县| 安义县| 铜川市| 偃师市| 鄄城县| 任丘市| 丰都县| 义乌市| 荃湾区| 自治县| 德化县| 盐源县| 石嘴山市| 武强县| 安龙县| 红桥区| 沭阳县| 隆安县| 鄄城县| 兴宁市| 韩城市| 湟中县| 河北省| 蒙城县| 渝北区| 南安市| 九台市| 新乐市| 沁阳市| 平遥县| 田林县| 文登市| 伊金霍洛旗| 大埔县| 盱眙县| 高唐县| 松江区| 若尔盖县|