I'm making simple Node.js app and I need to delete first line in file. Please is any way how to do it? I think that It will be possible with fs.write, but how?
4 Answers
Here is streamed version of removing first line from file.
As it uses streams, means you don't need to load whole file in memory, so it is way more efficient and fast, as well can work on very large files without filling memory on your hardware.
var Transform = require('stream').Transform;
var util = require('util');
// Transform sctreamer to remove first line
function RemoveFirstLine(args) {
if (! (this instanceof RemoveFirstLine)) {
return new RemoveFirstLine(args);
}
Transform.call(this, args);
this._buff = '';
this._removed = false;
}
util.inherits(RemoveFirstLine, Transform);
RemoveFirstLine.prototype._transform = function(chunk, encoding, done) {
if (this._removed) { // if already removed
this.push(chunk); // just push through buffer
} else {
// collect string into buffer
this._buff += chunk.toString();
// check if string has newline symbol
if (this._buff.indexOf('\n') !== -1) {
// push to stream skipping first line
this.push(this._buff.slice(this._buff.indexOf('\n') + 2));
// clear string buffer
this._buff = null;
// mark as removed
this._removed = true;
}
}
done();
};
And use it like so:
var fs = require('fs');
var input = fs.createReadStream('test.txt'); // read file
var output = fs.createWriteStream('test_.txt'); // write file
input // take input
.pipe(RemoveFirstLine()) // pipe through line remover
.pipe(output); // save to file
Another way, which is not recommended.
If your files are not large, and you don't mind loading them into memory, load file, remove line, save file, but it is slower and wont work well on large files.
var fs = require('fs');
var filePath = './test.txt'; // path to file
fs.readFile(filePath, function(err, data) { // read file to memory
if (!err) {
data = data.toString(); // stringify buffer
var position = data.toString().indexOf('\n'); // find position of new line element
if (position != -1) { // if new line element found
data = data.substr(position + 1); // subtract string based on first line length
fs.writeFile(filePath, data, function(err) { // write file
if (err) { // if error, report
console.log (err);
}
});
} else {
console.log('no lines found');
}
} else {
console.log(err);
}
});

- 22,846
- 4
- 51
- 67
-
thanks so much. Can I just ask, why should I read the file? I think that it's enaught to delete it with fs.write() without knowing content of file. What about replacing first line with ""? is it possible. For example in PHP, it's so easy to delete line – user2316602 Jun 28 '13 at 14:12
-
Abstractions in PHP have costs. You need to edit file - it means it has to be modified on HDD. To do so or technically you need to 'filter' buffer and then write the rest (after first line), with stream, or load file > remove line > save file. You can append anything to your string as you want. Please read general tutorials how to work with JavaScript, as I can clearly see lack of knowledge in general area of node and JS. `data = 'your text' + data.substr(position);` - will append some other text instead of first line. StackOverflow - is not support for coding, it is support for challenges. – moka Jun 28 '13 at 15:45
-
As well, please read this: http://stackoverflow.com/about and use rating system within website in order to mark answers as valid or mark them with 'down' arrow if they are misleading. – moka Jun 28 '13 at 15:46
-
This will fail if the file is larger than your RAM. – Anko - inactive in protest Jan 28 '14 at 17:41
-
Please provide better solution! – moka Jan 29 '14 at 11:55
-
Someone did -, please provide comment regarding it, so I could improve the answer! – moka Feb 21 '14 at 11:03
-
Technically you can open file, and start read characters till you get to newline character. Remember how many characters you've read. Then close reading file and then start stream from one file to another, and skip first number of bytes you've counted in first place, then normally pipe the rest. This will work perfectly on big files, and will be faster as well. – moka May 17 '14 at 22:42
-
1Provided streamed version of removing first line from file, providing ability to work with very large files. – moka Oct 30 '14 at 11:38
-
2I created a simple library based on this answer. It allows you to remove X amount of lines. All you do is pass the amount to the function and off it goes. It's called **striplines** and it's on [npmjs.org](https://www.npmjs.com/package/striplines) – DerekE Jul 07 '16 at 19:49
-
I had some issues with character encoding and newlines in the original answer, on Windows, with Portuguese data: I had to add `const endOfLine = require('os').EOL;` to the start of the file, and replace every `\n` with `endOfLine` And I had to specify `chunk.toString('binary');` to solve the character encoding issue. – Julien Apr 16 '19 at 09:37
Here is another way:
const fs = require('fs');
const filePath = './table.csv';
let csvContent = fs.readFileSync(filePath).toString().split('\n'); // read file and convert to array by line break
csvContent.shift(); // remove the the first element from array
csvContent = csvContent.join('\n'); // convert array back to string
fs.writeFileSync(filePath, csvContent);

- 1,847
- 20
- 19
-
2
-
People type juggle their variables *** Also people: "y my variable not workin properly? it all workd in dev?" – Gogol Sep 08 '22 at 18:58
-
3@ahe_borriglione The other solutions are "ugly" because they avoid loading the entire file into memory. Though this solution is very simple, many people who want to delete only the *first* line of a file are doing that because they are working with large files that they don't want to load into memory. It also uses synchronous file operations (instead of async) and parses the entire file into an array just to remove one element from it. In many simple scripts, it is a decent solution. But it's not necessarily a good solution for a lot of people looking for an answer to this. – Ben Muschol Sep 13 '22 at 17:04
Thanks to @Lilleman 's comment, I've made an amendment to the original solution, which requires a 3rd-party module "line-by-line" and can prevent memory overflow and racing condition while processing very large file.
const fs = require('fs');
const LineReader = require('line-by-line');
const removeLines = function(srcPath, destPath, count, cb) {
if(count <= 0) {
return cb();
}
var reader = new LineReader(srcPath);
var output = fs.createWriteStream(destPath);
var linesRemoved = 0;
var isFirstLine = true;
reader.on('line', (line) => {
if(linesRemoved < count) {
linesRemoved++;
return;
}
reader.pause();
var newLine;
if(isFirstLine) {
newLine = line;
isFirstLine = false;
} else {
newLine = '\n' + line;
}
output.write(newLine, () => {
reader.resume();
});
})
.on('error', (err) => {
reader.pause();
return cb(err);
})
.on('close', () => {
return cb();
})
}
---------------- original solution below---------------
Inspired by another answer, here is a revised stream version:
const fs = require('fs');
const readline = require('readline');
const removeFirstLine = function(srcPath, destPath, done) {
var rl = readline.createInterface({
input: fs.createReadStream(srcPath)
});
var output = fs.createWriteStream(destPath);
var firstRemoved = false;
rl.on('line', (line) => {
if(!firstRemoved) {
firstRemoved = true;
return;
}
output.write(line + '\n');
}).on('close', () => {
return done();
})
}
and it can be easily modified to remove certain amount of lines, by changing the 'firstRemoved' into a counter:
var linesRemoved = 0;
...
if(linesRemoved < LINES_TO_BE_REMOVED) {
linesRemoved++;
return;
}
...

- 345
- 3
- 7
-
1Please observe that the output.write() do have a callback to when the write is done. If your disk is slower at writing than on reading, the writes will queue up and your application will eventually crash if you rewrite a very large file. Also this creates a race condition; when done() is ran, it is not at all sure that the written file will contain all rows. – Lilleman Mar 16 '18 at 14:11
-
@Lilleman Thanks for your comment, I've made an amendment to the original solution. – Alvan Feb 18 '19 at 15:53
Here is a naive solution using the Promise-based file system APIs.
const fs = require('node:fs/promises')
const os = require('node:os')
async function removeLines(path, numLinesToRemove) {
const data = await fs.readFile(path, { encoding: 'utf-8' })
const newData = data
.split(os.EOL) // split data into array of strings
.slice(numLinesToRemove) // remove first N lines of array
.join(os.EOL) // join array into a single string
// overwrite original file with new data
return fs.writeFile(path, newData)
}

- 1