gpt4 book ai didi

node.js - 如何从txt文件中删除一行

转载 作者:IT老高 更新时间:2023-10-28 23:15:35 26 4
gpt4 key购买 nike

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

world
food

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

最佳答案

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

关于node.js - 如何从txt文件中删除一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38843016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com