如何删除文件末尾的一行并将其放在文件顶部?
How do I delete a line at the end of the file and put it at the top of the file?
这是我当前的代码:
const rl = require("readline");
const fs = require("fs");
const ri = rl.createInterface({
input: fs.createReadStream("dot-error.log"),
output: process.stdout,
console: false,
});
ri.on("line", function (line: string) {
const append: string = line.substring(line.indexOf("\n") + 1);
});
我将如何创建一个 for 循环来抓取文件末尾的行并粘贴到文件的顶部并删除该行(在文件的末尾) ? 谢谢!
删除最后一行然后放在最前面
var fs = require("fs");
var lines = fs.readFileSync("dot-error.log", 'utf8'); // read the file
lines = lines.trim().split('\n'); // remove empty lines and split using \n
var lastLine = lines.pop() // get last line
lines.unshift(lastLine); // prepend last line
fs.writeFileSync("dot-error.log", lines.join('\n')); // write
编辑:颠倒顺序
var lines = fs.readFileSync("dot-error.log", 'utf8');
lines = lines.trim().split('\n');
lines.reverse();
fs.writeFileSync("dot-error.log", lines.join('\n'));
这是我当前的代码:
const rl = require("readline");
const fs = require("fs");
const ri = rl.createInterface({
input: fs.createReadStream("dot-error.log"),
output: process.stdout,
console: false,
});
ri.on("line", function (line: string) {
const append: string = line.substring(line.indexOf("\n") + 1);
});
我将如何创建一个 for 循环来抓取文件末尾的行并粘贴到文件的顶部并删除该行(在文件的末尾) ? 谢谢!
删除最后一行然后放在最前面
var fs = require("fs");
var lines = fs.readFileSync("dot-error.log", 'utf8'); // read the file
lines = lines.trim().split('\n'); // remove empty lines and split using \n
var lastLine = lines.pop() // get last line
lines.unshift(lastLine); // prepend last line
fs.writeFileSync("dot-error.log", lines.join('\n')); // write
编辑:颠倒顺序
var lines = fs.readFileSync("dot-error.log", 'utf8');
lines = lines.trim().split('\n');
lines.reverse();
fs.writeFileSync("dot-error.log", lines.join('\n'));