Uint8Array vào tệp nodejs

Bất cứ khi nào một nút. js chấp nhận một đường dẫn hệ thống tệp trong một chuỗi (dòng A), nó thường cũng chấp nhận một thể hiện của

fs.writeFileSync(
  'existing-file.txt',
  'Appended line\n',
  {encoding: 'utf-8', flag: 'a'}
);
3 (dòng B)

Show

Chuyển đổi thủ công giữa các đường dẫn và URL

fs.writeFileSync(
  'existing-file.txt',
  'Appended line\n',
  {encoding: 'utf-8', flag: 'a'}
);
4 có vẻ dễ dàng nhưng lại có nhiều cạm bẫy đáng ngạc nhiên. mã hóa hoặc giải mã phần trăm, ký tự ổ đĩa Windows, v.v. Thay vào đó, tốt hơn là sử dụng hai chức năng sau

Chúng tôi không sử dụng URL tệp trong bài đăng trên blog này. Trong một bài đăng trên blog trong tương lai, chúng ta sẽ thấy các trường hợp sử dụng chúng

bộ đệm

Lớp

fs.writeFileSync(
  'existing-file.txt',
  'Appended line\n',
  {encoding: 'utf-8', flag: 'a'}
);
5 đại diện cho các chuỗi byte có độ dài cố định trên Nút. js. Nó là một lớp con của
fs.writeFileSync(
  'existing-file.txt',
  'Appended line\n',
  {encoding: 'utf-8', flag: 'a'}
);
6 (một TypedArray). Bộ đệm chủ yếu được sử dụng khi làm việc với các tệp nhị phân và do đó ít quan tâm đến bài đăng trên blog này

Bất cứ khi nào nút. js chấp nhận Bộ đệm, nó cũng chấp nhận Uint8Array. Do đó, với điều kiện là Uint8Arrays là đa nền tảng và Bộ đệm thì không, nên dùng cái trước

Bộ đệm có thể làm một việc mà Uint8Arrays không thể. mã hóa và giải mã văn bản trong các bảng mã khác nhau. Nếu chúng ta cần mã hóa hoặc giải mã UTF-8 trong Uint8Arrays, chúng ta có thể sử dụng lớp

fs.writeFileSync(
  'existing-file.txt',
  'Appended line\n',
  {encoding: 'utf-8', flag: 'a'}
);
7 hoặc lớp
fs.writeFileSync(
  'existing-file.txt',
  'Appended line\n',
  {encoding: 'utf-8', flag: 'a'}
);
8. Các lớp này có sẵn trên hầu hết các nền tảng JavaScript

> new TextEncoder().encode('café')
Uint8Array.of(99, 97, 102, 195, 169)
> new TextDecoder().decode(Uint8Array.of(99, 97, 102, 195, 169))
'café'

Nút. luồng js

Một số chức năng chấp nhận hoặc trả lại Node gốc. luồng js

  • fs.writeFileSync(
      'existing-file.txt',
      'Appended line\n',
      {encoding: 'utf-8', flag: 'a'}
    );
    
    9 là lớp của Node dành cho các luồng có thể đọc được. Mô-đun
    import {Writable} from 'node:stream';
    
    const nodeWritable = fs.createWriteStream(
      'new-file.txt', {encoding: 'utf-8'});
    const webWritableStream = Writable.toWeb(nodeWritable);
    
    const writer = webWritableStream.getWriter();
    try {
      await writer.write('First line\n');
      await writer.write('Second line\n');
      await writer.close();
    } finally {
      writer.releaseLock()
    }
    
    0 sử dụng
    import {Writable} from 'node:stream';
    
    const nodeWritable = fs.createWriteStream(
      'new-file.txt', {encoding: 'utf-8'});
    const webWritableStream = Writable.toWeb(nodeWritable);
    
    const writer = webWritableStream.getWriter();
    try {
      await writer.write('First line\n');
      await writer.write('Second line\n');
      await writer.close();
    } finally {
      writer.releaseLock()
    }
    
    1 là một phân lớp
  • import {Writable} from 'node:stream';
    
    const nodeWritable = fs.createWriteStream(
      'new-file.txt', {encoding: 'utf-8'});
    const webWritableStream = Writable.toWeb(nodeWritable);
    
    const writer = webWritableStream.getWriter();
    try {
      await writer.write('First line\n');
      await writer.write('Second line\n');
      await writer.close();
    } finally {
      writer.releaseLock()
    }
    
    2 là lớp của Node dành cho các luồng có thể ghi. Mô-đun
    import {Writable} from 'node:stream';
    
    const nodeWritable = fs.createWriteStream(
      'new-file.txt', {encoding: 'utf-8'});
    const webWritableStream = Writable.toWeb(nodeWritable);
    
    const writer = webWritableStream.getWriter();
    try {
      await writer.write('First line\n');
      await writer.write('Second line\n');
      await writer.close();
    } finally {
      writer.releaseLock()
    }
    
    0 sử dụng
    import {Writable} from 'node:stream';
    
    const nodeWritable = fs.createWriteStream(
      'new-file.txt', {encoding: 'utf-8'});
    const webWritableStream = Writable.toWeb(nodeWritable);
    
    const writer = webWritableStream.getWriter();
    try {
      await writer.write('First line\n');
      await writer.write('Second line\n');
      await writer.close();
    } finally {
      writer.releaseLock()
    }
    
    4 là một phân lớp

Thay vì luồng gốc, giờ đây chúng tôi có thể sử dụng luồng web đa nền tảng trên Node. js. Bài đăng trên blog “Sử dụng luồng web trên Node. js” giải thích cách

Đọc và ghi tệp

Đọc một tệp đồng bộ thành một chuỗi (tùy chọn. chia thành các dòng)

đọc tệp tại

import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'new-file.txt', {encoding: 'utf-8'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First line\n');
  await writer.write('Second line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
6 thành một chuỗi

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);

Ưu và nhược điểm của phương pháp này (so với. sử dụng một luồng)

  • chuyên nghiệp. Dễ sử dụng và đồng bộ. Đủ tốt cho nhiều trường hợp sử dụng
  • Côn. Không phải là một lựa chọn tốt cho các tệp lớn
    • Trước khi chúng tôi có thể xử lý dữ liệu, chúng tôi phải đọc toàn bộ dữ liệu đó

Tiếp theo, chúng ta sẽ xem xét việc chia chuỗi mà chúng ta đã đọc thành các dòng

Tách các dòng mà không bao gồm các đầu cuối dòng

Đoạn mã sau tách một chuỗi thành các dòng trong khi loại bỏ các đầu cuối dòng. Nó hoạt động với các bộ kết thúc dòng Unix và Windows

const RE_SPLIT_EOL = /\r?\n/;
function splitLines(str) {
  return str.split(RE_SPLIT_EOL);
}
assert.deepEqual(
  splitLines('there\r\nare\nmultiple\nlines'),
  ['there', 'are', 'multiple', 'lines']
);

“EOL” là viết tắt của “cuối dòng”. Chúng tôi chấp nhận cả bộ kết thúc dòng Unix (_______8_______7) và bộ kết thúc dòng Windows (

import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'new-file.txt', {encoding: 'utf-8'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First line\n');
  await writer.write('Second line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
8, như cái đầu tiên trong ví dụ trước). Để biết thêm thông tin, xem

Tách các dòng trong khi bao gồm các đầu cuối dòng

Đoạn mã sau chia một chuỗi thành các dòng trong khi bao gồm các đầu cuối dòng. Nó hoạt động với các bộ kết thúc dòng Unix và Windows (“EOL” là viết tắt của “end of line”)

Dòng A chứa một biểu thức chính quy với. Nó khớp với các vị trí trước đó là khớp với mẫu

import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'new-file.txt', {encoding: 'utf-8'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First line\n');
  await writer.write('Second line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
9 nhưng nó không chụp được bất cứ thứ gì. Do đó, nó không xóa bất kỳ thứ gì giữa các đoạn chuỗi mà chuỗi đầu vào được chia thành

Trên các công cụ không hỗ trợ xác nhận giao diện (xem bảng này), chúng ta có thể sử dụng giải pháp sau

Giải pháp này đơn giản, nhưng dài dòng hơn

Trong cả hai phiên bản của

import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'existing-file.txt', {encoding: 'utf-8', flags: 'a'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First appended line\n');
  await writer.write('Second appended line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
0, chúng tôi lại chấp nhận cả bộ kết thúc dòng Unix (
import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'new-file.txt', {encoding: 'utf-8'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First line\n');
  await writer.write('Second line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
7) và bộ kết thúc dòng Windows (
import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'new-file.txt', {encoding: 'utf-8'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First line\n');
  await writer.write('Second line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
8). Để biết thêm thông tin, xem

Đọc tệp qua luồng, từng dòng

Chúng tôi cũng có thể đọc tệp văn bản qua luồng

Chúng tôi đã sử dụng chức năng bên ngoài sau đây

Luồng web có thể lặp lại không đồng bộ, đó là lý do tại sao chúng ta có thể sử dụng vòng lặp

import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'existing-file.txt', {encoding: 'utf-8', flags: 'a'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First appended line\n');
  await writer.write('Second appended line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
3 để lặp lại qua các dòng

Nếu chúng ta không quan tâm đến các dòng văn bản, thì chúng ta không cần

import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'existing-file.txt', {encoding: 'utf-8', flags: 'a'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First appended line\n');
  await writer.write('Second appended line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
4, có thể lặp qua
import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'existing-file.txt', {encoding: 'utf-8', flags: 'a'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First appended line\n');
  await writer.write('Second appended line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
5 và lấy các đoạn có độ dài tùy ý

Thêm thông tin

Ưu và nhược điểm của phương pháp này (so với. đọc một chuỗi)

  • chuyên nghiệp. Hoạt động tốt với các tệp lớn
    • Chúng tôi có thể xử lý dữ liệu dần dần, theo từng phần nhỏ hơn và không phải đợi mọi thứ được đọc
  • Côn. Sử dụng phức tạp hơn và không đồng bộ

Viết một chuỗi vào một tệp một cách đồng bộ

ghi

import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'existing-file.txt', {encoding: 'utf-8', flags: 'a'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First appended line\n');
  await writer.write('Second appended line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
7 vào một tệp tại
import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'new-file.txt', {encoding: 'utf-8'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First line\n');
  await writer.write('Second line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
6. Nếu một tệp đã tồn tại ở đường dẫn đó, nó sẽ bị ghi đè

Đoạn mã sau cho thấy cách sử dụng chức năng này

fs.writeFileSync(
  'new-file.txt',
  'First line\nSecond line\n',
  {encoding: 'utf-8'}
);

Để biết thông tin về các đầu cuối dòng, xem

Ưu và nhược điểm (so với. sử dụng một luồng)

  • chuyên nghiệp. Dễ sử dụng và đồng bộ. Hoạt động cho nhiều trường hợp sử dụng
  • Côn. Không phù hợp với các tệp lớn

Nối một chuỗi vào một tệp (đồng bộ)

Đoạn mã sau nối thêm một dòng văn bản vào một tệp hiện có

fs.appendFileSync(
  'existing-file.txt',
  'Appended line\n',
  {encoding: 'utf-8'}
);

Chúng ta cũng có thể sử dụng

import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'existing-file.txt', {encoding: 'utf-8', flags: 'a'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First appended line\n');
  await writer.write('Second appended line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}
9 để thực hiện tác vụ này

fs.writeFileSync(
  'existing-file.txt',
  'Appended line\n',
  {encoding: 'utf-8', flag: 'a'}
);

Mã này gần giống với mã chúng tôi đã sử dụng để ghi đè lên nội dung hiện có (xem phần trước để biết thêm thông tin). Sự khác biệt duy nhất là chúng tôi đã thêm tùy chọn

const RE_EOL_REMOVE = /\r?\n$/;
function removeEol(line) {
  const match = RE_EOL_REMOVE.exec(line);
  if (!match) return line;
  return line.slice(0, match.index);
}

assert.equal(
  removeEol('Windows EOL\r\n'),
  'Windows EOL'
);
assert.equal(
  removeEol('Unix EOL\n'),
  'Unix EOL'
);
assert.equal(
  removeEol('No EOL'),
  'No EOL'
);
0. Giá trị
const RE_EOL_REMOVE = /\r?\n$/;
function removeEol(line) {
  const match = RE_EOL_REMOVE.exec(line);
  if (!match) return line;
  return line.slice(0, match.index);
}

assert.equal(
  removeEol('Windows EOL\r\n'),
  'Windows EOL'
);
assert.equal(
  removeEol('Unix EOL\n'),
  'Unix EOL'
);
assert.equal(
  removeEol('No EOL'),
  'No EOL'
);
1 có nghĩa là chúng tôi nối thêm dữ liệu. Các giá trị có thể khác (e. g. để báo lỗi nếu tệp chưa tồn tại) được giải thích trong

Coi chừng. Trong một số chức năng, tùy chọn này được đặt tên là

const RE_EOL_REMOVE = /\r?\n$/;
function removeEol(line) {
  const match = RE_EOL_REMOVE.exec(line);
  if (!match) return line;
  return line.slice(0, match.index);
}

assert.equal(
  removeEol('Windows EOL\r\n'),
  'Windows EOL'
);
assert.equal(
  removeEol('Unix EOL\n'),
  'Unix EOL'
);
assert.equal(
  removeEol('No EOL'),
  'No EOL'
);
0, trong một số chức năng khác là
const RE_EOL_REMOVE = /\r?\n$/;
function removeEol(line) {
  const match = RE_EOL_REMOVE.exec(line);
  if (!match) return line;
  return line.slice(0, match.index);
}

assert.equal(
  removeEol('Windows EOL\r\n'),
  'Windows EOL'
);
assert.equal(
  removeEol('Unix EOL\n'),
  'Unix EOL'
);
assert.equal(
  removeEol('No EOL'),
  'No EOL'
);
3

Viết nhiều chuỗi vào một tệp qua luồng

Đoạn mã sau sử dụng một luồng để ghi nhiều chuỗi vào một tệp

________số 8_______

Chúng tôi đã sử dụng các chức năng sau

Thêm thông tin

Ưu và nhược điểm (so với. viết một chuỗi)

  • chuyên nghiệp. Hoạt động tốt với các tệp lớn vì chúng tôi có thể ghi dữ liệu tăng dần, theo từng phần nhỏ hơn
  • Côn. Sử dụng phức tạp hơn và không đồng bộ

Nối nhiều chuỗi vào một tệp qua luồng (không đồng bộ)

Đoạn mã sau sử dụng một luồng để nối thêm văn bản vào một tệp hiện có

import {Writable} from 'node:stream';

const nodeWritable = fs.createWriteStream(
  'existing-file.txt', {encoding: 'utf-8', flags: 'a'});
const webWritableStream = Writable.toWeb(nodeWritable);

const writer = webWritableStream.getWriter();
try {
  await writer.write('First appended line\n');
  await writer.write('Second appended line\n');
  await writer.close();
} finally {
  writer.releaseLock()
}

Mã này gần giống với mã chúng tôi đã sử dụng để ghi đè lên nội dung hiện có (xem phần trước để biết thêm thông tin). Sự khác biệt duy nhất là chúng tôi đã thêm tùy chọn

const RE_EOL_REMOVE = /\r?\n$/;
function removeEol(line) {
  const match = RE_EOL_REMOVE.exec(line);
  if (!match) return line;
  return line.slice(0, match.index);
}

assert.equal(
  removeEol('Windows EOL\r\n'),
  'Windows EOL'
);
assert.equal(
  removeEol('Unix EOL\n'),
  'Unix EOL'
);
assert.equal(
  removeEol('No EOL'),
  'No EOL'
);
3. Giá trị
const RE_EOL_REMOVE = /\r?\n$/;
function removeEol(line) {
  const match = RE_EOL_REMOVE.exec(line);
  if (!match) return line;
  return line.slice(0, match.index);
}

assert.equal(
  removeEol('Windows EOL\r\n'),
  'Windows EOL'
);
assert.equal(
  removeEol('Unix EOL\n'),
  'Unix EOL'
);
assert.equal(
  removeEol('No EOL'),
  'No EOL'
);
1 có nghĩa là chúng tôi nối thêm dữ liệu. Các giá trị có thể khác (e. g. để báo lỗi nếu tệp chưa tồn tại) được giải thích trong

Coi chừng. Trong một số chức năng, tùy chọn này được đặt tên là

const RE_EOL_REMOVE = /\r?\n$/;
function removeEol(line) {
  const match = RE_EOL_REMOVE.exec(line);
  if (!match) return line;
  return line.slice(0, match.index);
}

assert.equal(
  removeEol('Windows EOL\r\n'),
  'Windows EOL'
);
assert.equal(
  removeEol('Unix EOL\n'),
  'Unix EOL'
);
assert.equal(
  removeEol('No EOL'),
  'No EOL'
);
0, trong một số chức năng khác là
const RE_EOL_REMOVE = /\r?\n$/;
function removeEol(line) {
  const match = RE_EOL_REMOVE.exec(line);
  if (!match) return line;
  return line.slice(0, match.index);
}

assert.equal(
  removeEol('Windows EOL\r\n'),
  'Windows EOL'
);
assert.equal(
  removeEol('Unix EOL\n'),
  'Unix EOL'
);
assert.equal(
  removeEol('No EOL'),
  'No EOL'
);
3

Xử lý các đầu cuối dòng trên các nền tảng

Than ôi, không phải tất cả các nền tảng đều có các ký tự kết thúc dòng giống nhau đánh dấu cuối dòng (EOL)

  • Trên Windows, EOL là
    import {Writable} from 'node:stream';
    
    const nodeWritable = fs.createWriteStream(
      'new-file.txt', {encoding: 'utf-8'});
    const webWritableStream = Writable.toWeb(nodeWritable);
    
    const writer = webWritableStream.getWriter();
    try {
      await writer.write('First line\n');
      await writer.write('Second line\n');
      await writer.close();
    } finally {
      writer.releaseLock()
    }
    
    8
  • Trên Unix (bao gồm. macOS), EOL là
    import {Writable} from 'node:stream';
    
    const nodeWritable = fs.createWriteStream(
      'new-file.txt', {encoding: 'utf-8'});
    const webWritableStream = Writable.toWeb(nodeWritable);
    
    const writer = webWritableStream.getWriter();
    try {
      await writer.write('First line\n');
      await writer.write('Second line\n');
      await writer.close();
    } finally {
      writer.releaseLock()
    }
    
    7

Để xử lý EOL theo cách hoạt động trên tất cả các nền tảng, chúng tôi có thể sử dụng một số chiến lược

Đọc kết thúc dòng

Khi đọc văn bản, tốt nhất là nhận ra cả hai EOL

Điều đó có thể trông như thế nào khi chia văn bản thành các dòng? . Điều đó cho phép chúng tôi thay đổi ít nhất có thể nếu chúng tôi sửa đổi những dòng đó và ghi chúng vào một tệp

Khi xử lý các dòng có EOL, đôi khi rất hữu ích khi loại bỏ chúng – e. g. thông qua chức năng sau

const RE_EOL_REMOVE = /\r?\n$/;
function removeEol(line) {
  const match = RE_EOL_REMOVE.exec(line);
  if (!match) return line;
  return line.slice(0, match.index);
}

assert.equal(
  removeEol('Windows EOL\r\n'),
  'Windows EOL'
);
assert.equal(
  removeEol('Unix EOL\n'),
  'Unix EOL'
);
assert.equal(
  removeEol('No EOL'),
  'No EOL'
);

Viết dấu đầu dòng

Khi nói đến việc viết các dấu kết thúc dòng, chúng ta có hai lựa chọn

  • chứa EOL của nền tảng hiện tại
  • Chúng tôi có thể phát hiện định dạng EOL của tệp đầu vào và sử dụng định dạng đó khi chúng tôi thay đổi tệp đó

Duyệt và tạo thư mục

Duyệt qua một thư mục

Hàm sau duyệt qua một thư mục và liệt kê tất cả các thư mục con của nó (con của nó, con của con của nó, v.v. )

Chúng tôi đã sử dụng chức năng này

  • trả về con của thư mục tại
    fs.mkdirSync(thePath, options?): undefined | string
    
    3
    • Nếu tùy chọn
      fs.mkdirSync(thePath, options?): undefined | string
      
      4 là
      fs.mkdirSync(thePath, options?): undefined | string
      
      5, hàm trả về các mục nhập thư mục, phiên bản của. Chúng có các thuộc tính như
      • fs.mkdirSync(thePath, options?): undefined | string
        
        7
      • fs.mkdirSync(thePath, options?): undefined | string
        
        8
      • fs.mkdirSync(thePath, options?): undefined | string
        
        9
      • assert.equal(
          fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
          'there\r\nare\nmultiple\nlines'
        );
        
        00
    • Nếu tùy chọn
      fs.mkdirSync(thePath, options?): undefined | string
      
      4 là
      assert.equal(
        fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
        'there\r\nare\nmultiple\nlines'
      );
      
      02 hoặc bị thiếu, hàm trả về chuỗi có tên tệp

Đoạn mã sau hiển thị

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
03 đang hoạt động

Tạo thư mục (assert.equal( fs.readFileSync('text-file.txt', {encoding: 'utf-8'}), 'there\r\nare\nmultiple\nlines' ); 04, assert.equal( fs.readFileSync('text-file.txt', {encoding: 'utf-8'}), 'there\r\nare\nmultiple\nlines' ); 05)

Chúng ta có thể sử dụng để tạo các thư mục

fs.mkdirSync(thePath, options?): undefined | string

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
06 xác định cách hàm tạo thư mục tại
fs.mkdirSync(thePath, options?): undefined | string
3

  • Nếu

    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    08 bị thiếu hoặc
    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    02, thì ____14_______10 trả về ___14_______11 và một ngoại lệ được đưa ra nếu

    • Một thư mục (hoặc tệp) đã tồn tại tại
      fs.mkdirSync(thePath, options?): undefined | string
      
      3
    • Thư mục mẹ của
      fs.mkdirSync(thePath, options?): undefined | string
      
      3 không tồn tại
  • Nếu

    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    08 là
    fs.mkdirSync(thePath, options?): undefined | string
    
    5

    • Không sao nếu đã có thư mục tại
      fs.mkdirSync(thePath, options?): undefined | string
      
      3
    • Các thư mục tổ tiên của
      fs.mkdirSync(thePath, options?): undefined | string
      
      3 được tạo khi cần
    • assert.equal(
        fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
        'there\r\nare\nmultiple\nlines'
      );
      
      10 trả về đường dẫn của thư mục mới được tạo đầu tiên

Đây là

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
10 đang hoạt động

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
0

liệt kê tất cả hậu duệ của thư mục tại

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
21

Đảm bảo rằng một thư mục mẹ tồn tại

Nếu chúng tôi muốn thiết lập cấu trúc tệp lồng nhau theo yêu cầu, chúng tôi không thể luôn chắc chắn rằng các thư mục tổ tiên tồn tại khi chúng tôi tạo một tệp mới. Sau đó, chức năng sau đây sẽ giúp

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
1

Ở đây chúng ta có thể thấy

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
22 đang hoạt động (dòng A)

Tạo một thư mục tạm thời

tạo một thư mục tạm thời. Nó nối thêm 6 ký tự ngẫu nhiên vào

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
24, tạo một thư mục ở đường dẫn mới và trả về đường dẫn đó

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
24 không nên kết thúc bằng chữ “X” viết hoa vì một số nền tảng thay thế các chữ X ở cuối bằng các ký tự ngẫu nhiên

Nếu chúng tôi muốn tạo thư mục tạm thời của mình bên trong thư mục tạm thời toàn cầu dành riêng cho hệ điều hành, chúng tôi có thể sử dụng

Điều quan trọng cần lưu ý là các thư mục tạm thời không tự động bị xóa khi một Nút. tập lệnh js kết thúc. Chúng tôi phải tự xóa nó hoặc dựa vào hệ điều hành để dọn dẹp định kỳ thư mục tạm thời toàn cầu của nó (điều này có thể làm hoặc không làm)

Sao chép, đổi tên, di chuyển tập tin hoặc thư mục

Sao chép tập tin hoặc thư mục

sao chép một tập tin hoặc thư mục từ

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
28 sang
assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
29. tùy chọn thú vị

  • assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    08 (mặc định.
    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    02). Các thư mục (bao gồm cả những thư mục trống) chỉ được sao chép nếu tùy chọn này là
    fs.mkdirSync(thePath, options?): undefined | string
    
    5
  • assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    33 (mặc định.
    fs.mkdirSync(thePath, options?): undefined | string
    
    5). Nếu
    fs.mkdirSync(thePath, options?): undefined | string
    
    5, các tệp hiện có sẽ bị ghi đè. Nếu
    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    02, các tệp hiện có được giữ nguyên
    • Trong trường hợp thứ hai, đặt
      assert.equal(
        fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
        'there\r\nare\nmultiple\nlines'
      );
      
      37 thành
      fs.mkdirSync(thePath, options?): undefined | string
      
      5 dẫn đến lỗi bị ném nếu đường dẫn tệp xung đột
  • assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    39 là chức năng cho phép chúng tôi kiểm soát tệp nào được sao chép
  • assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    40 (mặc định.
    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    02). Nếu
    fs.mkdirSync(thePath, options?): undefined | string
    
    5, các bản sao trong
    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    29 có cùng dấu thời gian như bản gốc trong
    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    28

Đây là chức năng trong hành động

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
2

liệt kê tất cả hậu duệ của thư mục tại

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
21

Đổi tên hoặc di chuyển tệp hoặc thư mục

đổi tên hoặc di chuyển tệp hoặc thư mục từ

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
48 thành
assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
49

Hãy sử dụng chức năng này để đổi tên một thư mục

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
3

Ở đây chúng tôi sử dụng chức năng để di chuyển một tập tin

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
4

liệt kê tất cả hậu duệ của thư mục tại

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
21

Xóa tệp hoặc thư mục

Xóa tệp và thư mục tùy ý (shell. assert.equal( fs.readFileSync('text-file.txt', {encoding: 'utf-8'}), 'there\r\nare\nmultiple\nlines' ); 52, assert.equal( fs.readFileSync('text-file.txt', {encoding: 'utf-8'}), 'there\r\nare\nmultiple\nlines' ); 53)

xóa một tệp hoặc thư mục tại

fs.mkdirSync(thePath, options?): undefined | string
3. tùy chọn thú vị

  • assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    08 (mặc định.
    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    02). Các thư mục (bao gồm cả những thư mục trống) chỉ bị xóa nếu tùy chọn này là
    fs.mkdirSync(thePath, options?): undefined | string
    
    5
  • assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    33 (mặc định.
    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    02). Nếu
    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    02, một ngoại lệ sẽ được đưa ra nếu không có tệp hoặc thư mục tại
    fs.mkdirSync(thePath, options?): undefined | string
    
    3

Hãy sử dụng

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
63 để xóa tệp

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
5

Ở đây chúng tôi sử dụng

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
63 để xóa đệ quy một thư mục không trống

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
6

liệt kê tất cả hậu duệ của thư mục tại

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
21

Xóa một thư mục trống (shell. assert.equal( fs.readFileSync('text-file.txt', {encoding: 'utf-8'}), 'there\r\nare\nmultiple\nlines' ); 67)

xóa một thư mục trống (một ngoại lệ được đưa ra nếu một thư mục không trống)

Đoạn mã sau cho thấy chức năng này hoạt động như thế nào

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
7

liệt kê tất cả hậu duệ của thư mục tại

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
21

Xóa thư mục

Một tập lệnh lưu đầu ra của nó vào một thư mục

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
71, thường cần xóa
assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
71 trước khi bắt đầu. Xóa mọi tệp trong
assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
71 để nó trống. Hàm sau thực hiện điều đó

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
8

Chúng tôi đã sử dụng hai chức năng hệ thống tập tin

Đây là một ví dụ về việc sử dụng

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
74

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
9

Thùng rác các tập tin hoặc thư mục

Thư viện

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
75 di chuyển tệp và thư mục vào thùng rác. Nó hoạt động trên macOS, Windows và Linux (nơi hỗ trợ bị hạn chế và cần trợ giúp). Đây là một ví dụ từ tệp readme của nó

const RE_SPLIT_EOL = /\r?\n/;
function splitLines(str) {
  return str.split(RE_SPLIT_EOL);
}
assert.deepEqual(
  splitLines('there\r\nare\nmultiple\nlines'),
  ['there', 'are', 'multiple', 'lines']
);
0

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
76 chấp nhận Mảng chuỗi hoặc chuỗi làm tham số đầu tiên. Bất kỳ chuỗi nào cũng có thể là một mẫu hình cầu (có dấu hoa thị và các ký tự meta khác)

Đọc và thay đổi các mục hệ thống tập tin

Kiểm tra nếu một tập tin hoặc thư mục tồn tại

trả về

fs.mkdirSync(thePath, options?): undefined | string
5 nếu tệp hoặc thư mục tồn tại tại
fs.mkdirSync(thePath, options?): undefined | string
3

const RE_SPLIT_EOL = /\r?\n/;
function splitLines(str) {
  return str.split(RE_SPLIT_EOL);
}
assert.deepEqual(
  splitLines('there\r\nare\nmultiple\nlines'),
  ['there', 'are', 'multiple', 'lines']
);
1

liệt kê tất cả hậu duệ của thư mục tại

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
21

Kiểm tra số liệu thống kê của một tập tin. Nó có phải là một thư mục? .   

trả về một thể hiện của

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
83 với thông tin về tệp hoặc thư mục tại
fs.mkdirSync(thePath, options?): undefined | string
3

Thú vị

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
85

  • assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    86 (mặc định.
    fs.mkdirSync(thePath, options?): undefined | string
    
    5). Điều gì xảy ra nếu không có thực thể tại
    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    88?
    • Nếu tùy chọn này là
      fs.mkdirSync(thePath, options?): undefined | string
      
      5, một ngoại lệ sẽ được đưa ra
    • Nếu là
      assert.equal(
        fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
        'there\r\nare\nmultiple\nlines'
      );
      
      02, thì trả về
      assert.equal(
        fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
        'there\r\nare\nmultiple\nlines'
      );
      
      11
  • assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    92 (mặc định.
    assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    02). Nếu
    fs.mkdirSync(thePath, options?): undefined | string
    
    5, hàm này sử dụng bigint cho các giá trị số (chẳng hạn như dấu thời gian, xem bên dưới)

Thuộc tính của các thể hiện của

  • Đây là loại mục nhập hệ thống tập tin nào?
    • assert.equal(
        fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
        'there\r\nare\nmultiple\nlines'
      );
      
      96
    • assert.equal(
        fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
        'there\r\nare\nmultiple\nlines'
      );
      
      97
    • assert.equal(
        fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
        'there\r\nare\nmultiple\nlines'
      );
      
      98
  • assert.equal(
      fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
      'there\r\nare\nmultiple\nlines'
    );
    
    99 là kích thước tính bằng byte
  • Dấu thời gian
    • Có ba loại dấu thời gian
      • const RE_SPLIT_EOL = /\r?\n/;
        function splitLines(str) {
          return str.split(RE_SPLIT_EOL);
        }
        assert.deepEqual(
          splitLines('there\r\nare\nmultiple\nlines'),
          ['there', 'are', 'multiple', 'lines']
        );
        
        00. thời điểm truy cập cuối cùng
      • const RE_SPLIT_EOL = /\r?\n/;
        function splitLines(str) {
          return str.split(RE_SPLIT_EOL);
        }
        assert.deepEqual(
          splitLines('there\r\nare\nmultiple\nlines'),
          ['there', 'are', 'multiple', 'lines']
        );
        
        01. thời điểm sửa đổi cuối cùng
      • const RE_SPLIT_EOL = /\r?\n/;
        function splitLines(str) {
          return str.split(RE_SPLIT_EOL);
        }
        assert.deepEqual(
          splitLines('there\r\nare\nmultiple\nlines'),
          ['there', 'are', 'multiple', 'lines']
        );
        
        02. thời gian sáng tạo
    • Mỗi dấu thời gian này có thể được chỉ định bằng ba đơn vị khác nhau – ví dụ:
      const RE_SPLIT_EOL = /\r?\n/;
      function splitLines(str) {
        return str.split(RE_SPLIT_EOL);
      }
      assert.deepEqual(
        splitLines('there\r\nare\nmultiple\nlines'),
        ['there', 'are', 'multiple', 'lines']
      );
      
      03
      • const RE_SPLIT_EOL = /\r?\n/;
        function splitLines(str) {
          return str.split(RE_SPLIT_EOL);
        }
        assert.deepEqual(
          splitLines('there\r\nare\nmultiple\nlines'),
          ['there', 'are', 'multiple', 'lines']
        );
        
        00. trường hợp của
        const RE_SPLIT_EOL = /\r?\n/;
        function splitLines(str) {
          return str.split(RE_SPLIT_EOL);
        }
        assert.deepEqual(
          splitLines('there\r\nare\nmultiple\nlines'),
          ['there', 'are', 'multiple', 'lines']
        );
        
        05
      • const RE_SPLIT_EOL = /\r?\n/;
        function splitLines(str) {
          return str.split(RE_SPLIT_EOL);
        }
        assert.deepEqual(
          splitLines('there\r\nare\nmultiple\nlines'),
          ['there', 'are', 'multiple', 'lines']
        );
        
        06. mili giây kể từ Kỷ nguyên POSIX
      • const RE_SPLIT_EOL = /\r?\n/;
        function splitLines(str) {
          return str.split(RE_SPLIT_EOL);
        }
        assert.deepEqual(
          splitLines('there\r\nare\nmultiple\nlines'),
          ['there', 'are', 'multiple', 'lines']
        );
        
        07. nano giây kể từ Kỷ nguyên POSIX (yêu cầu tùy chọn
        assert.equal(
          fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
          'there\r\nare\nmultiple\nlines'
        );
        
        92)

Trong ví dụ sau, chúng tôi sử dụng

const RE_SPLIT_EOL = /\r?\n/;
function splitLines(str) {
  return str.split(RE_SPLIT_EOL);
}
assert.deepEqual(
  splitLines('there\r\nare\nmultiple\nlines'),
  ['there', 'are', 'multiple', 'lines']
);
09 để triển khai hàm
const RE_SPLIT_EOL = /\r?\n/;
function splitLines(str) {
  return str.split(RE_SPLIT_EOL);
}
assert.deepEqual(
  splitLines('there\r\nare\nmultiple\nlines'),
  ['there', 'are', 'multiple', 'lines']
);
10

const RE_SPLIT_EOL = /\r?\n/;
function splitLines(str) {
  return str.split(RE_SPLIT_EOL);
}
assert.deepEqual(
  splitLines('there\r\nare\nmultiple\nlines'),
  ['there', 'are', 'multiple', 'lines']
);
2

liệt kê tất cả hậu duệ của thư mục tại

assert.equal(
  fs.readFileSync('text-file.txt', {encoding: 'utf-8'}),
  'there\r\nare\nmultiple\nlines'
);
21

Hãy xem xét ngắn gọn các chức năng để thay đổi thuộc tính tệp

Các chức năng để làm việc với các liên kết cứng

Các chức năng để làm việc với các liên kết tượng trưng

Các chức năng sau hoạt động trên các liên kết tượng trưng mà không cần hủy bỏ hội nghị của chúng (lưu ý tiền tố tên “l”)

Làm cách nào để chuyển đổi bộ đệm thành tệp nodejs?

readFile() , bạn có thể chuyển vùng đệm thành văn bản từ tệp bằng cách sử dụng. toString('utf8') . const fs = yêu cầu('fs'); . readFileSync('. /bưu kiện.

Uint8Array có phải là bộ đệm không?

Uint8Array là một mảng byte đa năng có sẵn trong cả nodejs và trình duyệt. Bộ đệm là một lớp con của Uint8Array chỉ có trong nodejs (vì lý do lịch sử). cả hai đều được sử dụng chủ yếu để thao tác dữ liệu nhị phân (byte).

Làm cách nào để chuyển đổi bộ đệm thành chuỗi nodejs?

Tóm lại, thật dễ dàng để chuyển đổi một đối tượng Bộ đệm thành một chuỗi bằng cách sử dụng phương thức toString() . Thông thường, bạn sẽ muốn mã hóa UTF-8 mặc định nhưng có thể chỉ định một mã hóa khác nếu cần. Để chuyển đổi từ một chuỗi thành một đối tượng Bộ đệm, hãy sử dụng Bộ đệm tĩnh.

Làm cách nào để đọc tệp trong nút js?

Ba cách đọc tệp trong nút. .
Đọc tệp theo cách Promise. Cách Hứa hẹn cho phép chúng tôi sử dụng tính năng Javascript không đồng bộ hiện đại - không đồng bộ và chờ đợi. .
Đọc File với cách Callback. Cách tiếp cận cho cách Gọi lại là sử dụng fs. .
Đọc tệp theo cách đồng bộ