我有以下文本文件("test.txt"),我想在node.js中操作:
world
food
Run Code Online (Sandbox Code Playgroud)
我想删除第一行,以便food
成为第一行.我怎样才能做到这一点?
小智 16
var fs = require('fs')
fs.readFile(filename, 'utf8', function(err, data)
{
if (err)
{
// check and handle err
}
var linesExceptFirst = data.split('\n').slice(1).join('\n');
fs.writeFile(filename, linesExceptFirst);
});
Run Code Online (Sandbox Code Playgroud)
我刚刚遇到需要能够排除文件中的几行。这是我如何使用简单的节点函数来完成此操作。
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.");
});
})
Run Code Online (Sandbox Code Playgroud)
使用替换
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');
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8092 次 |
最近记录: |