在行号nodejs处插入字符串 [英] Insert string at line number nodejs

查看:208
本文介绍了在行号nodejs处插入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要修改的文件.有没有一种方法可以将字符串插入到特定行号的文件中?与 NodeJS

I have a file that I would like to modify. Is there a way to insert a string to a file at a specific line number? with NodeJS

我真的非常感谢您为我提供帮助

I really thank you for helping me out

推荐答案

只要文本文件没有那么大,您就应该能够将文本文件读入数组,在特定的元素中插入一个元素行索引,然后将数组输出回到文件.我在下面放了一些示例代码-确保更改'file.txt'"Your String"和特定的lineNumber.

As long as the text file isn't that large, you should be able to just read in the text file into an array, insert an element into the specific line index, and then output the array back to the file. I've put some sample code below - make sure you change 'file.txt', "Your String" and the specific lineNumber.

免责声明,我还没有时间测试以下代码:

var fs = require('fs');

var data = fs.readFileSync('file.txt').toString().split("\n");
data.splice(lineNumber, 0, "Your String");
var text = data.join("\n");

fs.writeFile('file.txt', text, function (err) {
  if (err) return console.log(err);
});

这篇关于在行号nodejs处插入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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