gpt4 book ai didi

node.js - 在 Node.js 中,如何读取文件、在指定行追加字符串或从某一行删除字符串?

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:34 25 4
gpt4 key购买 nike

我需要打开一个现有的 JavaScript 文件,检查此字符串是否存在:

var LocalStrategy = require('passport-local').Strategy;

如果没有,则将其与其余 require() 行一起附加到顶部。

在另一种情况下,我需要检查该字符串是否存在,如果存在,我想删除该行。

我看过 fs.readFilefs.writeFilefs.open 但我不认为它能够做到这一点我需要的。有什么建议吗?

最佳答案

这是一个简化的脚本:

var fs = require('fs');

var search = "var LocalStrategy = require('passport-local').Strategy;";


function append (line) {
line = line || 0;

var body = fs.readFileSync('example.js').toString();

if (body.indexOf(search) < 0 ) {

body = body.split('\n');
body.splice(line + 1,0,search);
body = body.filter(function(str){ return str; }); // remove empty lines
var output = body.join('\n');
fs.writeFileSync('example.js', output);
}
}


function remove () {

var body = fs.readFileSync('example.js').toString();
var idx = body.indexOf(search);

if (idx >= 0 ) {
var output = body.substr(0, idx) + body.substr(idx + search.length);
fs.writeFileSync('example.js', output);
}

}

关于node.js - 在 Node.js 中,如何读取文件、在指定行追加字符串或从某一行删除字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23036918/

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