If you want to store your "keywords" as a valid json file, you might need to read file, add data and write again:
const fs = require('fs')
const startKeywordsFile = 'startkeywords.json'
// create an empty json if not exists
if (!fs.existsSync(startKeywordsFile)) {
fs.writeFileSync(startKeywordsFile, '[]')
}
let words = JSON.parse(fs.readFileSync(startKeywordsFile, 'utf8'))
function addWord(newWord) {
if (words.includes(newWord)) {
// already exists
return
}
words.push(newWord)
fs.writeFileSync(startKeywordsFile, JSON.stringify(words, null, 4))
}
addWord('hi')
addWord('hello')
startkeywords.json
:
[
"hi",
"hello"
]
Keep in mind it might have performance issue with a large list. If you want to save your keywords as plain text (one word a line, not valid json), you can use fs.appendFileSync
to append your file without having to rewrite the entire file everytime.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…