Reputation: 21
Everytime I run my script, undefined is in the beginning and I have no idea why. I want to convert this file
user:pass
user:pass
user:pass
into
username: user
password: pass
username: user
password: pass
username: user
password: pass
but everytime I run it it ends up being..
undefinedusername: user
password: pass
username: user
password: pass
username: user
password: pass
My NodeJS script is the following:
var fs = require('fs');
var data = fs.readFileSync('details.txt', 'utf-8');
var updatedText;
data = data.replace(/:/g, '\n');
lines = data.split("\n");
for (line in lines) {
if (line % 2 == 0) {
updatedText += `username: ${lines[line]}\n`
} else if (line % 2 == 1) {
updatedText += `password: ${lines[line]}\n`
}
}
fs.writeFile('converted.txt', updatedText, function (err) {
if (err) throw err;
console.log('Saved!');
});
All help is of course appreciated! :)
Upvotes: 0
Views: 309
Reputation: 4743
updatedText
has value undefined. When you do updatedText += ..., the first time when it runs, it adds undefined to the value
var updatedText = ""
will fix the issue
Here is a snippet showing the issue:
var a;
console.log(a+"text1")
var b = ""
console.log(b+"text2")
Upvotes: 1