如何从txt文件中删除一行 [英] How to remove one line from a txt file

查看:119
本文介绍了如何从txt文件中删除一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 node.js 中操作以下文本文件(test.txt"):

I have the following text file ("test.txt") that I want to manipulate in node.js:

world
food

我想删除第一行,以便 food 成为第一行.我该怎么做?

I want to remove the first line so that food becomes the first line instead. How can I do that?

推荐答案

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);
});

这篇关于如何从txt文件中删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆