How to overwrite existing dotenv entry with new value [duplicate] - node.js

I am trying to simply replace a line in a text file using JavaScript.
The idea is:
var oldLine = 'This is the old line';
var newLine = 'This new line replaces the old line';
Now i want to specify a file, find the oldLine and replace it with the newLine and save it.
Anyone who can help me here?

Just building on Shyam Tayal's answer, if you want to replace an entire line matching your string, and not just an exact matching string do the following instead:
fs.readFile(someFile, 'utf8', function(err, data) {
let searchString = 'to replace';
let re = new RegExp('^.*' + searchString + '.*$', 'gm');
let formatted = data.replace(re, 'a completely different line!');
fs.writeFile(someFile, formatted, 'utf8', function(err) {
if (err) return console.log(err);
});
});
The 'm' flag will treat the ^ and $ meta characters as the beginning and end of each line, not the beginning or end of the whole string.
So the above code would transform this txt file:
one line
a line to replace by something
third line
into this:
one line
a completely different line!
third line

This should do it
var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {
var formatted = data.replace(/This is the old line/g, 'This new line replaces the old line');
fs.writeFile(someFile, formatted, 'utf8', function (err) {
if (err) return console.log(err);
});
});

Related

Apply regex to .txt file node.js

I'm trying to escape quotes in txt file using node.js and regex.
My code looks like this:
const fs = require("fs");
const utf8 = require("utf8");
var dirname = ".\\f\\";
const regex = new RegExp(`(?<=".*)"(?=.*"$)`, "gm");
fs.readFile(dirname + "test.txt", (error, data) => {
if (error) {
throw error;
}
var d = data.toString();
d = utf8.encode(d)
console.log(`File: ${typeof d}`); //string
// d = `Another string\n"Test "here"."\n"Another "here"."\n"And last one here."`;
console.log(`Text: ${typeof d}`); //string
var re = d.replace(regex, '\\"');
console.log(`Result:\n${re}`);
/* Another string
"Test \"here\"."
"Another \"here\"."
"And last one here."
*/
});
The problem is:
When I remove comment from the line, everything works fine. But if i read the text from the file it doesn't want to work.
Thanks for any comments on this.
Well.. turns out the problem was in file encoding. The file was encoded in UTF-16, not in UTF-8. Node.js wasn't giving me any signs of wrong encoding, so well, nice.

How to delete lines of text from file with createWriteStream with Node.js?

I'm trying to update a huge text document by deleting text that is dynamically received from an array. I cannot use readFileSync because the file is way too large so I have to stream it. The problem im encountering is the function deletes everything instead of only deleting what's in the array. Perhaps im not understanding how to properly delete something from a stream. How can this be done?
largeFile_example.txt
test_domain_1
test_domain_2
test_domain_3
test_domain_4
test_domain_5
test_domain_6
test_domain_7
test_domain_8
test_domain_9
test_domain_10
stream.js
const es = require('event-stream');
const fs = require('fs');
//array of domains to delete
var domains = ['test_domain_2','test_domain_6','test_domain_8'];
//loop
domains.forEach(function(domain){
//domain to delete
var dom_to_delete = domain;
//stream
var s = fs
.createReadStream('largeFile_example.txt')
.pipe(es.split())
.pipe(
es
.mapSync(function(line) {
//check if found in text
if(line === dom_to_delete){
//delete
var newValue = dom_to_delete.replace(line, '');
fs.createWriteStream('largeFile_example.txt', newValue, 'utf-8');
}
})
.on('error', function(err) {
console.log('Error while reading file.', err);
})
.on('end', function() {
//...do something
}),
);
})
You can simply use readline interface with the streams and you can read line by line. When you encounter any domain from the array just don't add it.
You can use for-of with async/await
const fs = require('fs');
const readline = require('readline');
async function processLine() {
const fileStream = fs.createReadStream('yourfile');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: crlfDelay recognize all instances of CR LF
// ('\r\n') in file as a single line break.
for await (const line of rl) {
// each line will be here as domain
// create a write stream and append it to the file
// line by line using { flag: a }
}
}
processLine();
To delete the domains from the existing file, you need to follow these steps:
Need to read the file as a stream.
Replace the text you don't want with the '' using regex or replace method.
add the updated content to the temp file or a new file.
There is no way you can read from one point and update the same line. I mean I am not aware of such a technique in Node.js(will be happy to know that). So that's why you need to create a new file and once updated remove the old file.
Maybe you can add some more value to how you code it as I am not sure why you want to do that. If your file is not large you can do that in-place, but your case is different.

Add string on top file with NodeJS

I would like add string on the top of my js file. Actuly, it's on the end :
var file = './public/js/app.bundleES6.js',
string = '// My string';
fs.appendFileSync(file, string);
Do you have idea for add my string on the first line ?
Thank you !
I think there is no built-in way to insert at the beginning of the file in Node.js.
But you can use readFileSync and writeFile methods of fs to resolve this issue
It will append string at top of the file
Try this
Method#1
var fs = require('fs');
var data = fs.readFileSync('./example.js').toString().split("\n");
data.splice(0, 0, "Append the string whatever you want at top" );
var text = data.join("\n");
fs.writeFile('./example.js', text, function (err) {
if (err) return err;
});
Method#2
If you are relying on to use third party module then you can use prepend module to add the string at the top as suggested by #robertklep.
var prepend = require('prepend');
prepend(FileName, 'String to be appended', function(error) {
if (error)
console.error(error.message);
});

How can I change a specific line in a file with node js?

I want to change a specific line in a text file using node js with the fs module.
Is there a more elegant way then loading the file into an array?
Old File:
Line 1
Line 2
Line 3
New File:
Line 1
something new
Line 3
Thanks for your replies!
Try using this:
var fs = require('fs')
fs.readFile("your file", {encoding: 'utf8'}, function (err,data) {
var formatted = data.replace(/This is the old line/g, 'This new line replaces the old line');
fs.writeFile("your file", formatted, 'utf8', function (err) {
if (err) return console.log(err);
});
});
If this doesn't work, visit https://www.npmjs.com/package/replace-in-file.

nodejs read file and split with \u001

I have a hadoop file that has \u001 as a delimiter, and I try to read the data and split records by \u001. But the length is always 1, that is the data is not been spilt.
var fs = require('fs');
var buffer = fs.readFile('20140820075209.txt', function (err, data) {
console.log(data.toString());
console.log(data.toString().split('\\u001').length);
});
You shouldn't escape the backslash if you want the actual character:
console.log(data.toString().split('\u0001').length);
or:
console.log(data.toString().split('\x01').length);

Resources