Node.js 实用笔记(三)功能模块

  • Post author:
  • Post category:其他


  • 在 Node.js 中使用文件描述符

    在与位于文件系统中的文件进行交互之前,需要先获取文件的描述符。文件描述符是使用 fs 模块提供的 open() 方法打开文件后返回的:

    const fs = require('fs')
    
    fs.open('/Users/joe/test.txt', 'r', (err, fd) => {
         
      //fd 是文件描述符。
    })
    

    注意,将 r 作为 fs.open() 调用的第二个参数。

    r+ 打开文件用于读写。

    w+ 打开文件用于读写,将流定位到文件的开头。如果文件不存在则创建文件。

    a 打开文件用于写入,将流定位到文件的末尾。如果文件不存在则创建文件。

    a+ 打开文件用于读写,将流定位到文件的末尾。如果文件不存在则创建文件。

  • Node.js 文件属性

    使用 fs 模块提供的 stat() 方法。调用时传入文件的路径,一旦 Node.js 获得文件的详细信息,则会调用传入的回调函数,并带上两个参数:错误消息和文件属性:

    const fs = require('fs')
    fs.stat('/Users/joe/test.txt', (err, stats) => {
         
      if (err) {
         
        console.error(err)
        return
      }
      //可以访问 `stats` 中的文件属性
    })
    
  • Node.js 文件路径

    const notes = '/users/joe/notes.txt'
    
    path.dirname(notes) // /users/joe
    path.basename(notes) // notes.txt
    path.extname(notes) // .txt
    

    使用路径:

    可以使用 path.join() 连接路径的两个或多个片段:

    const name = 'joe'
    	path.join('/', 'users', name, 'notes.txt') //'/users/joe/notes.txt'
    

    可以使用 path.resolve() 获得相对路径的绝对路径计算:

    path.resolve('joe.txt') //'/Users/joe/joe.txt' 如果从主文件夹运行。
    

    在此示例中,Node.js 只是简单地将 /joe.txt 附加到当前工作目录。 如果指定第二个文件夹参数,则 resolve 会使用第一个作为第二个的基础:

    path.resolve('tmp', 'joe.txt') //'/Users/joe/tmp/joe.txt' 如果从主文件夹运行。
    

    如果第一个参数以斜杠开头,则表示它是绝对路径:

    path.resolve('/etc', 'joe.txt') //'/etc/joe.txt'
    

    path.normalize() 是另一个有用的函数,当包含诸如 .、… 或双斜杠之类的相对说明符时,其会尝试计算实际的路径:

    path.normalize('/users/joe/..//test.txt') ///users/test.txt
    

    解析和规范化都不会检查路径是否存在。 其只是根据获得的信息来计算路径。

  • 使用 Node.js 读取文件

    const fs = require('fs')
    
    fs.readFile('/Users/joe/test.txt', 'utf8' , (err, data) => {
         
      if (err) {
         
        console.error(err)
        return
      }
      console.log(data)
    })
    
    const fs = require('fs')
    
    try {
         
      const data = fs.readFileSync('/Users/joe/test.txt', 'utf8')
      console.log(data)
    } catch (err) {
         
      console.error(err)
    }
    

    fs.readFile() 和 fs.readFileSync() 都会在返回数据之前将文件的全部内容读取到内存中。这意味着大文件会对内存的消耗和程序执行的速度产生重大的影响。在这种情况下,更好的选择是使用流来读取文件的内容。

  • 使用 Node.js 写入文件

     const fs = require(



版权声明:本文为u011783277原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。