Reputation: 58
I have the following code that is supposed to call an api using the object key value and then open a text file and replace the text that matches the key with the API data. To simplify I've removed the API to just loop through they obj keys and then attempt to replace.
const fs = require('fs')
const storage = require('./db/storage')
const keys = Object.keys(storage.MOVIES);
for (const key of keys) {
fs.readFile('./db/movies_prebuilt.txt', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
//THIS LINE DOESNT WORK using key. but does work using an actual
string.
var result = data.replace(key, "NOTWORKING");
fs.writeFile('./movies.md', result, 'utf8', function (err) {
if (err) return console.log(err);
});
});
}
The db/storage snippet looks like this:
exports.MOVIES = {
"Matrix_Score": "tt0133093",
"2001_Space_Score": "tt0062622"
...
}
And The replacement text inside looks like this
### Matrix_Score
And I have changed the for loop to data.replace("Matrix_Score","WORKING");
and that works perfectly fine. Is it not possible to use the key as a string? The only reason I want to use it, is so I dont have to write another array or object with all the names, when I have it already.
cheers!
Upvotes: 0
Views: 784
Reputation: 3227
I think this following code may be closer to what I am understanding the intention is. fs.readFile
returns all of the file contents, and you likely want to replace all of the keys, not just the last one. Also no need to read the file multiple times:
const fs = require('fs')
const storage = require('./db/storage')
const keys = Object.keys(storage.MOVIES);
fs.readFile('./db/movies_prebuilt.txt', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
for (const key of keys) {
data = data.toString().replace(key, "NOTWORKING");
}
fs.writeFile('./movies.md', data, 'utf8', function (err) {
if (err) return console.log(err);
});
});
EDIT to add back the original point
fs.readFile
typically returns a Buffer which needs to be .toString
'd to be manipulated.
Upvotes: 1