Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

node.js - How to write a file with fs.writeFileSync in a list

Im trying to make my first "AI" that store the words that i use with a "chat bot" everytime that i open like if i use "hello" and later i use "Heya" the chatbot will write these words on a json file And use these words randomly to greet me when i open the program

(At this moment i just trying to write the words on a list, the bot greeting me with these words i already don't created)

heres the code that i tryied:

const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('Hello! ', (answer) => {
  // TODO: Log the answer in a database
  console.log(`The ${answer} word has stored :)`);
  
  fs.writeFileSync(__dirname + '/startkeywords.json', JSON.stringify(answer, null, 4));
  console.log('created at' + __dirname);

  rl.close();
});

but, when i execute the program and say something,its writes,but its not on a list that just writes, so i'm trying to write the file on a list like this:

list example

help pls

question from:https://stackoverflow.com/questions/65599056/how-to-write-a-file-with-fs-writefilesync-in-a-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...