阿西河

所有教程

公众号
🌙
阿西河前端的公众号

我的收藏

    最近访问  (文章)

      教程列表

      抓包专区
      测试专区

      Node.js fs filehandle.truncate

      Node.js fs filehandle.truncate(len)

      新增于: v10.0.0

      • len < integer> Default: 0
      • Returns:

      Truncates the file then resolves the Promise with no arguments upon success.

      If the file was larger than len bytes, only the first len bytes will be retained in the file.

      For example, the following program retains only the first four bytes of the file:

      const fs = require('fs');
      const fsPromises = fs.promises;
      
      console.log(fs.readFileSync('temp.txt', 'utf8'));
      // Prints: Node.js
      
      async function doTruncate() {
        let filehandle = null;
        try {
          filehandle = await fsPromises.open('temp.txt', 'r+');
          await filehandle.truncate(4);
        } finally {
          if (filehandle) {
            // close the file if it is opened.
            await filehandle.close();
          }
        }
        console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints: Node
      }
      
      doTruncate().catch(console.error);
      

      If the file previously was shorter than len bytes, it is extended, and the extended part is filled with null bytes ('\0'):

      const fs = require('fs');
      const fsPromises = fs.promises;
      
      console.log(fs.readFileSync('temp.txt', 'utf8'));
      // Prints: Node.js
      
      async function doTruncate() {
        let filehandle = null;
        try {
          filehandle = await fsPromises.open('temp.txt', 'r+');
          await filehandle.truncate(10);
        } finally {
          if (filehandle) {
            // close the file if it is opened.
            await filehandle.close();
          }
        }
        console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints Node.js\0\0\0
      }
      doTruncate().catch(console.error);
      

      The last three bytes are null bytes ('\0'), to compensate the over-truncation.


      更多内容请参考:Node.js fs 文件系统,或者通过 点击对应菜单 进行查看;


      目录
      本文目录
      目录