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!
keysactually contains the values you expect?keyis a variable that holds a string value. A string value is always a string.Matrix_Scorekey if you doconsole.log(key, key === "Matrix_Score");. What if you doconsole.log(key, key.length)?