Hướng dẫn nodejs remove line from file - nodejs xóa dòng khỏi tệp

Tôi có tệp văn bản sau ("test.txt") mà tôi muốn thao tác trong node.js:

world
food

Tôi muốn loại bỏ dòng đầu tiên để food trở thành dòng đầu tiên thay thế. Làm thế nào tôi có thể làm điều đó?

Hướng dẫn nodejs remove line from file - nodejs xóa dòng khỏi tệp

Hỏi ngày 9 tháng 8 năm 2016 lúc 5:52Aug 9, 2016 at 5:52

1

var fs = require('fs')
fs.readFile(filename, 'utf8', function(err, data)
{
    if (err)
    {
        // check and handle err
    }
    // data is the file contents as a single unified string
    // .split('\n') splits it at each new-line character and all splits are aggregated into an array (i.e. turns it into an array of lines)
    // .slice(1) returns a view into that array starting at the second entry from the front (i.e. the first element, but slice is zero-indexed so the "first" is really the "second")
    // .join() takes that array and re-concatenates it into a string
    var linesExceptFirst = data.split('\n').slice(1).join('\n');
    fs.writeFile(filename, linesExceptFirst, function(err, data) { if (err) {/** check and handle err */} });
});

zr0gravity7

2.5281 Huy hiệu vàng9 Huy hiệu bạc26 Huy hiệu đồng1 gold badge9 silver badges26 bronze badges

Đã trả lời ngày 9 tháng 8 năm 2016 lúc 6:21Aug 9, 2016 at 6:21

Hướng dẫn nodejs remove line from file - nodejs xóa dòng khỏi tệp

Scott Mscott mScott M

5231 Huy hiệu vàng5 Huy hiệu bạc13 Huy hiệu đồng1 gold badge5 silver badges13 bronze badges

1

Tôi chỉ bắt gặp sự cần thiết phải loại trừ một số dòng trong một tệp. Đây là cách tôi đã làm nó với một chức năng nút đơn giản.

const fs = require('fs');

const removeLines = (data, lines = []) => {
    return data
        .split('\n')
        .filter((val, idx) => lines.indexOf(idx) === -1)
        .join('\n');
}

fs.readFile(fileName, 'utf8', (err, data) => {
    if (err) throw err;

    // remove the first line and the 5th and 6th lines in the file
    fs.writeFile(fileName, removeLines(data, [0, 4, 5]), 'utf8', function(err) {
        if (err) throw err;
        console.log("the lines have been removed.");
    });
})

Đã trả lời ngày 27 tháng 2 năm 2019 lúc 14:03Feb 27, 2019 at 14:03

Sử dụng thay thế

const fs = require('fs');

function readWriteSync() {
  var data = fs.readFileSync(filepath, 'utf-8');

  // replace 'world' together with the new line character with empty
  var newValue = data.replace(/world\n/, '');

  fs.writeFileSync(filepath, newValue, 'utf-8');
}

Đã trả lời ngày 17 tháng 12 năm 2020 lúc 9:30Dec 17, 2020 at 9:30

user3113626user3113626user3113626

5997 Huy hiệu bạc16 Huy hiệu Đồng7 silver badges16 bronze badges

Khi một tệp phát triển kích thước (nghĩ về tệp nhật ký), tôi muốn xóa 5 dòng đầu tiên hoặc 5000 byte đầu tiên. Từ một tìm kiếm trên web, nó nói rằng tôi có thể sử dụng sed -i để xóa các dòng tại chỗ. Nhưng tôi đang tìm kiếm một tiện ích thư viện Node.js (như fs.x()) có thể xóa byte khỏi một tệp, không chỉ đọc chúng. Điều này có thể bằng cách nào đó?

Lưu ý: Tôi chắc chắn đang tìm cách tránh phương pháp truyền thống để đọc toàn bộ tệp vào phân tách bộ nhớ theo các dòng, chuyển 5 đầu tiên và sau đó ghi đè lên tệp với các nội dung mới - điều này không thực sự hoạt động và có khả năng tải lên một tệp lớn trong Bộ nhớ không có Bueno.

Đó không phải là một vấn đề đơn giản. Tôi không nghĩ rằng các hệ điều hành thường cung cấp tính năng này và tôi không thể nghĩ ra một cách hiệu quả để thực hiện điều này trên hầu hết các hệ thống tệp. Làm thế nào đĩa "xóa" một phần của tệp mà không phải viết lại mọi thứ? .

Lưu ý: Tôi chắc chắn đang tìm cách tránh phương pháp truyền thống để đọc toàn bộ tệp vào phân tách bộ nhớ theo các dòng, chuyển 5 đầu tiên và sau đó ghi đè lên tệp với các nội dung mới - điều này không thực sự hoạt động và có khả năng tải lên một tệp lớn trong Bộ nhớ không có Bueno.

Đó không phải là một vấn đề đơn giản. Tôi không nghĩ rằng các hệ điều hành thường cung cấp tính năng này và tôi không thể nghĩ ra một cách hiệu quả để thực hiện điều này trên hầu hết các hệ thống tệp. Làm thế nào đĩa "xóa" một phần của tệp mà không phải viết lại mọi thứ? .

Hướng dẫn nodejs remove line from file - nodejs xóa dòng khỏi tệp

Điều đó thực sự, âm thanh không hiệu quả khủng khiếp. Nhưng bạn có thể sử dụng một luồng, bỏ qua một vài dòng đầu tiên và ghi mọi thứ khác vào một tệp mới, sau đó di chuyển tệp mới vào đường dẫn của tệp gốc.

Hoặc, nếu bạn đang tìm kiếm một loại bộ đệm nhật ký tròn, bạn có thể sử dụng một addon gốc để quản lý nội dung tệp bằng cách sử dụng fseek nguyên thủy?

OK, fs.truncate tồn tại, nhưng nó cắt ngắn từ đầu đường mòn, không phải từ đầu.

Đó là một lớp bao bọc mỏng xung quanh cắt ngắn2

Có thể là thời gian cho API fs.seek(path, seek, callback)?

var fs = require('fs')
fs.readFile(filename, 'utf8', function(err, data)
{
    if (err)
    {
        // check and handle err
    }
    // data is the file contents as a single unified string
    // .split('\n') splits it at each new-line character and all splits are aggregated into an array (i.e. turns it into an array of lines)
    // .slice(1) returns a view into that array starting at the second entry from the front (i.e. the first element, but slice is zero-indexed so the "first" is really the "second")
    // .join() takes that array and re-concatenates it into a string
    var linesExceptFirst = data.split('\n').slice(1).join('\n');
    fs.writeFile(filename, linesExceptFirst, function(err, data) { if (err) {/** check and handle err */} });
});
0

Ngoài ra, chúng ta có thể quá tải fs.truncate với một tùy chọn cho biết từ đâu để cắt ngắn?

cc @nodejs/fs

@gireeshpunathil Làm thế nào chúng ta sẽ thực hiện nó mà không viết lại toàn bộ tệp?

var fs = require('fs')
fs.readFile(filename, 'utf8', function(err, data)
{
    if (err)
    {
        // check and handle err
    }
    // data is the file contents as a single unified string
    // .split('\n') splits it at each new-line character and all splits are aggregated into an array (i.e. turns it into an array of lines)
    // .slice(1) returns a view into that array starting at the second entry from the front (i.e. the first element, but slice is zero-indexed so the "first" is really the "second")
    // .join() takes that array and re-concatenates it into a string
    var linesExceptFirst = data.split('\n').slice(1).join('\n');
    fs.writeFile(filename, linesExceptFirst, function(err, data) { if (err) {/** check and handle err */} });
});
1 chỉ có thể xóa từ cuối tệp.

@tniessen - Hãy để tôi làm rõ:

Tùy chọn 1: Triển khai

var fs = require('fs')
fs.readFile(filename, 'utf8', function(err, data)
{
    if (err)
    {
        // check and handle err
    }
    // data is the file contents as a single unified string
    // .split('\n') splits it at each new-line character and all splits are aggregated into an array (i.e. turns it into an array of lines)
    // .slice(1) returns a view into that array starting at the second entry from the front (i.e. the first element, but slice is zero-indexed so the "first" is really the "second")
    // .join() takes that array and re-concatenates it into a string
    var linesExceptFirst = data.split('\n').slice(1).join('\n');
    fs.writeFile(filename, linesExceptFirst, function(err, data) { if (err) {/** check and handle err */} });
});
2 và phơi bày
var fs = require('fs')
fs.readFile(filename, 'utf8', function(err, data)
{
    if (err)
    {
        // check and handle err
    }
    // data is the file contents as a single unified string
    // .split('\n') splits it at each new-line character and all splits are aggregated into an array (i.e. turns it into an array of lines)
    // .slice(1) returns a view into that array starting at the second entry from the front (i.e. the first element, but slice is zero-indexed so the "first" is really the "second")
    // .join() takes that array and re-concatenates it into a string
    var linesExceptFirst = data.split('\n').slice(1).join('\n');
    fs.writeFile(filename, linesExceptFirst, function(err, data) { if (err) {/** check and handle err */} });
});
3 Syscall cho người dùng - và để họ đối phó với sự phức tạp của việc viết ở đúng vị trí và di chuyển xung quanh con trỏ tệp.

@gireeshpunathil MHHH có cắt ngắn thực sự xem xét phần bù hiện tại trong tệp không? Vì vậy, nó có thực sự loại bỏ các bộ phận trước khi bù hiện tại? Điều đó làm tôi ngạc nhiên.

@tniessen - API FS.Truncate hiện tại không; Đó là đề xuất của tôi. Nếu bạn đang nói về Syscall

var fs = require('fs')
fs.readFile(filename, 'utf8', function(err, data)
{
    if (err)
    {
        // check and handle err
    }
    // data is the file contents as a single unified string
    // .split('\n') splits it at each new-line character and all splits are aggregated into an array (i.e. turns it into an array of lines)
    // .slice(1) returns a view into that array starting at the second entry from the front (i.e. the first element, but slice is zero-indexed so the "first" is really the "second")
    // .join() takes that array and re-concatenates it into a string
    var linesExceptFirst = data.split('\n').slice(1).join('\n');
    fs.writeFile(filename, linesExceptFirst, function(err, data) { if (err) {/** check and handle err */} });
});
1, tôi không biết làm thế nào nó được thực hiện, nhưng nó là gì, những chi tiết triển khai đó có thể được trừu tượng hóa trong API JS.

Nếu bạn đang nói về Syscall

var fs = require('fs')
fs.readFile(filename, 'utf8', function(err, data)
{
    if (err)
    {
        // check and handle err
    }
    // data is the file contents as a single unified string
    // .split('\n') splits it at each new-line character and all splits are aggregated into an array (i.e. turns it into an array of lines)
    // .slice(1) returns a view into that array starting at the second entry from the front (i.e. the first element, but slice is zero-indexed so the "first" is really the "second")
    // .join() takes that array and re-concatenates it into a string
    var linesExceptFirst = data.split('\n').slice(1).join('\n');
    fs.writeFile(filename, linesExceptFirst, function(err, data) { if (err) {/** check and handle err */} });
});
1, tôi không biết làm thế nào nó được thực hiện, nhưng nó là gì, những chi tiết triển khai đó có thể được trừu tượng hóa trong API JS.

Vâng, ý tôi là hệ thống. Theo như tôi biết, nó không hỗ trợ cắt ngắn sự khởi đầu của tệp, chỉ có kết thúc.