搜尋
首頁web前端html教學Node基础篇(文件操作)_html/css_WEB-ITnose

文件操作

相关模块

Node内核提供了很多与文件操作相关的模块,每个模块都提供了一些最基本的操作API,在NPM中也有社区提供的功能包

fs:

基础的文件操作 API

path:

提供和路径相关的操作 API

readline:

用于读取大文本文件,一行一行读

fs-extra(第三方):

https://www.npmjs.com/package/fs-extra

同步或异步调用

  • fs模块对文件的几乎所有操作都有同步和异步两种形式
  • 例如:readFile() 和 readFileSync()
  • 区别:
    • 同步调用会阻塞代码的执行,异步则不会
    • 异步调用会将读取任务下达到任务队列,直到任务执行完成才会回调
    • 异常处理方面,同步必须使用 try catch 方式,异步可以通过回调函数的第一个参数

路径模块

在文件操作的过程中,都必须使用物理路径(绝对路径),path模块提供了一系列与路径相关的 API

console.log('join用于拼接多个路径部分,并转化为正常格式');  const temp = path.join(__dirname, '..', 'lyrics', './友谊之光.lrc');  console.log(temp);console.log('获取路径中的文件名');  console.log(path.basename(temp));console.log('获取路径中的文件名并排除扩展名');  console.log(path.basename(temp, '.lrc'));console.log('====================================');console.log('获取不同操作系统的路径分隔符');  console.log(process.platform + '的分隔符为 ' + path.delimiter);console.log('一般用于分割环境变量');  console.log(process.env.PATH.split(path.delimiter));console.log('====================================');console.log('获取一个路径中的目录部分');  console.log(path.dirname(temp));console.log('====================================');console.log('获取一个路径中最后的扩展名');  console.log(path.extname(temp));console.log('====================================');console.log('将一个路径解析成一个对象的形式');  const pathObject = path.parse(temp);  console.log(pathObject);console.log('====================================');console.log('将一个路径对象再转换为一个字符串的形式');  // pathObject.name = '我终于失去了你';pathObject.base = '我终于失去了你.lrc';  console.log(pathObject);console.log(path.format(pathObject));console.log('====================================');console.log('获取一个路径是不是绝对路径');  console.log(path.isAbsolute(temp));  console.log(path.isAbsolute('../lyrics/爱的代价.lrc'));console.log('====================================');console.log('将一个路径转换为当前系统默认的标准格式,并解析其中的./和../');  console.log(path.normalize('c:/develop/demo\\hello/../world/./a.txt'));console.log('====================================');console.log('获取第二个路径相对第一个路径的相对路径');  console.log(path.relative(__dirname, temp));console.log('====================================');console.log('以类似命令行cd命令的方式拼接路径');  console.log(path.resolve(temp, 'c:/', './develop', '../application'));console.log('====================================');console.log('获取不同平台中路径的分隔符(默认)');  console.log(path.sep);console.log('====================================');console.log('允许在任意平台下以WIN32的方法调用PATH对象');  // console.log(path.win32);console.log(path === path.win32);console.log('====================================');console.log('允许在任意平台下以POSIX的方法调用PATH对象');  console.log(path === path.posix);  

源码地址: https://github.com/nodejs/node/blob/master/lib/path.js

文件读取

Node中文件读取的方式主要有:

fs.readFile(file[, options], callback(error, data))

fs.readFile('c:\\demo\1.txt', 'utf8', (err, data) => {    if (err) throw err;  console.log(data);});

fs.readFileSync(file[, options])

try {    const data = fs.readFileSync('c:\\demo\1.txt', 'utf8');  console.log(data);} catch(e) {  // 文件不存在,或者权限错误  throw e;}

fs.createReadStream(path[, options])

const stream = fs.createReadStream('c:\\demo\1.txt');  let data = ''  stream.on('data', (trunk) => {    data += trunk;});stream.on('end', () => {    console.log(data);});

由于Windows平台下默认文件编码是GBK,在Node中不支持,可以通过 iconv-lite解决

Readline模块逐行读取文本内容

const readline = require('readline');  const fs = require('fs');const rl = readline.createInterface({    input: fs.createReadStream('sample.txt')});rl.on('line', (line) => {    console.log('Line from file:', line);});

文件写入

Node中文件写入的方式主要有:

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

fs.writeFile('c:\\demo\a.txt', new Date(), (error) => {    console.log(error);});

fs.writeFileSync(file, data[, options])

try {    fs.writeFileSync('c:\\demo\a.txt', new Date());} catch (error) {  // 文件夹不存在,或者权限错误  console.log(error);}

fs.createWriteStream(path[,option])

var streamWriter = fs.createWriteStream('c:\\demo\a.txt');  setInterval(() => {    streamWriter.write(`${new Date}\n`, (error) => {    console.log(error);  });}, 1000);

文件写入

fs.appendFile(file,data[,options],callback(err))

// 相比较之前文件流的方式,这种方式不会占用文件资源,append完成就会释放setInterval(() => {    fs.appendFile('c:\\demo\a.txt',`${new Date}\n`, (error) => {    console.log(error);  });}, 1000);

fs.appendFileSync(file,data[,options])

setInterval(() => {    fs.appendFileSync('c:\\demo\a.txt',`${new Date}\n`);}, 1000);

其他常见文件操作

验证路径是否存在(过时的API)

  • fs.exists(path,callback(exists))
  • fs.existsSync(path) // => 返回布尔类型 exists

获取文件信息

  • fs.stat(path,callback(err,stats))
  • fs.statSync(path) // => 返回一个fs.Stats实例

移动文件或重命名文件或目录

与命令行相同,重命名操作也可以实现文件移动

  • fs.rename(oldPath,newPath,callback)
  • fs.renameSync(oldPath,newPath)

删除文件

  • fs.unlink(path,callback(err))
  • fs.unlinkSync(path)

其他常见文件夹操作

创建一个目录

  • fs.mkdir(path[,model],callback)
  • fs.mkdirSync(path[,model])

删除一个空目录

  • fs.rmdir(path,callback)
  • fs.rmdirSync(path)

读取一个目录

  • fs.readdir(path,callback(err,files))
  • fs.readdirSync(path) // => 返回files

文件监视

利用文件监视实现自动 markdown 文件转换

  • 相关链接:

    1. https://github.com/chjj/marked
    2. https://github.com/Browsersync/browser-sync
  • 实现思路:

    1. 利用 fs模块的文件监视功能监视指定MD文件
    2. 当文件发生变化后,借助 marked包提供的 markdownto html功能将改变后的MD文件转换为HTML
    3. 再将得到的HTML替换到模版中
    4. 最后利用BrowserSync模块实现浏览器自动刷新
const fs = require('fs');  const path = require('path');  var marked = require('marked');  var bs = require('browser-sync').create();var target = path.join(__dirname, process.argv[2] || './README.md');  var filename = path.basename(target, path.extname(target)) + '.html';  var targetHtml = path.join(path.dirname(target), filename);bs.init({    server: path.dirname(target),  index: filename,  notify: false});bs.reload(filename);var template = `<!DOCTYPE html>  <html lang="en">  <head>    <meta charset="UTF-8">  <title></title>  <style>{{{styles}}}</style></head>  <body>    <article class="markdown">    {{{body}}}  </article></body>  </html>  `;fs.readFile(path.join(__dirname, './markdown.css'), 'utf8', (error, css) => {    if (error) throw error;  template = template.replace('{{{styles}}}', css);  var handler = (current, previous) => {    fs.readFile(target, 'utf8', (error, content) => {      var html = template.replace('{{{body}}}', marked(content));      fs.writeFile(targetHtml, html, (error) => {        if (!error) {          console.log(`updated@${new Date()}`);          bs.reload(filename);        }      });    });  };  handler();  fs.watchFile(target, { interval: 100 }, handler);});

缓冲区处理

什么是缓冲区

  • 缓冲区就是内存中操作数据的容器
  • 只是数据容器而已
  • 通过缓冲区可以很方便的操作二进制数据
  • 而且在大文件操作时必须有缓冲区

为什么要有缓冲区

  • JavaScript是比较擅长处理字符串,但是早期的应用场景主要用于处理HTML文档,不会有太大篇幅的数据处理,也不会接触到二进制的数据。
  • 而在Node中操作数据、网络通信是没办法完全以字符串的方式操作的,简单来说
  • 所以在Node中引入了一个二进制的缓冲区的实现:Buffer
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
HTML標籤和HTML屬性有什麼區別?HTML標籤和HTML屬性有什麼區別?May 14, 2025 am 12:01 AM

HTMLtagsdefinethestructureofawebpage,whileattributesaddfunctionalityanddetails.1)Tagslike,,andoutlinethecontent'splacement.2)Attributessuchassrc,class,andstyleenhancetagsbyspecifyingimagesources,styling,andmore,improvingfunctionalityandappearance.

HTML的未來:進化和趨勢HTML的未來:進化和趨勢May 13, 2025 am 12:01 AM

HTML的未來將朝著更加語義化、功能化和模塊化的方向發展。 1)語義化將使標籤更明確地描述內容,提升SEO和無障礙訪問。 2)功能化將引入新元素和屬性,滿足用戶需求。 3)模塊化將支持組件化開發,提高代碼復用性。

為什麼HTML屬性對Web開發很重要?為什麼HTML屬性對Web開發很重要?May 12, 2025 am 12:01 AM

htmlattributesarecrucialinwebdevelopment forcontrollingBehavior,外觀和功能

Alt屬性的目的是什麼?為什麼重要?Alt屬性的目的是什麼?為什麼重要?May 11, 2025 am 12:01 AM

alt屬性是HTML中標籤的重要部分,用於提供圖片的替代文本。 1.當圖片無法加載時,alt屬性中的文本會顯示,提升用戶體驗。 2.屏幕閱讀器使用alt屬性幫助視障用戶理解圖片內容。 3.搜索引擎索引alt屬性中的文本,提高網頁的SEO排名。

HTML,CSS和JavaScript:示例和實際應用HTML,CSS和JavaScript:示例和實際應用May 09, 2025 am 12:01 AM

HTML、CSS和JavaScript在網頁開發中的作用分別是:1.HTML用於構建網頁結構;2.CSS用於美化網頁外觀;3.JavaScript用於實現動態交互。通過標籤、樣式和腳本,這三者共同構築了現代網頁的核心功能。

如何在標籤上設置lang屬性?為什麼這很重要?如何在標籤上設置lang屬性?為什麼這很重要?May 08, 2025 am 12:03 AM

設置標籤的lang屬性是優化網頁可訪問性和SEO的關鍵步驟。 1)在標籤中設置lang屬性,如。 2)在多語言內容中,為不同語言部分設置lang屬性,如。 3)使用符合ISO639-1標準的語言代碼,如"en"、"fr"、"zh"等。正確設置lang屬性可以提高網頁的可訪問性和搜索引擎排名。

HTML屬性的目的是什麼?HTML屬性的目的是什麼?May 07, 2025 am 12:01 AM

htmlattributeseresene forenhancingwebelements'functionalityandAppearance.TheyAdDinformationTodeFineBehavior,外觀和互動,使網站互動,響應式,visalalyAppealing.AttributesLikutesLikeSlikEslikesrc,href,href,href,類,類型,類型,和dissabledtransfransformformformformformformformformformformformformformformforment

您如何在HTML中創建列表?您如何在HTML中創建列表?May 06, 2025 am 12:01 AM

toCreateAlistInHtml,useforforunordedlistsandfororderedlists:1)forunorderedlists,wrapitemsinanduseforeachItem,RenderingeringAsabulletedList.2)fororderedlists,useandfornumberedlists,useandfornumberedlists,casundfornumberedlists,casundfornthetthetthetthetthetthetthetttributefordforderfordforderforderentnumberingsnumberingsnumberingStys。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具