简体   繁体   中英

Read Specificst from txt file - javascript

I begin with variables userId, userPoints and userCodes.

And I want a text file with the following contents:

[userId: user9283], [userPoints: 45], [userCodes: kjsdnosd, sndjncjks, nsdjknckjs]

In javascript, how would you go about writing gathered data to a txt file using that format, changing when the variable changes and grabbing for example just the contents of userCodes in an array when asked for.

This would be somewhat like a database, but locally for a small amount of data. I have looked into fs.WriteFile and AppendFile, but not sure how to go about reading specific contents of a line and/or adding to specific contents, checking if a userid is already in there, and if so, appending it.

Thank you :)

var fs = require('file-system');

fs.writeFile('SavedAccounts.txt', "", function (err) {
  if (err) {
    console.log("write failed")
  } else {
    console.log("write success")
  }
})

fs.appendFile('AccountsToBeMade.txt', userID, function (err) {
  if (err) {
    console.log("write failed")
  } else {
    console.log("write success")

If you intend to only use the data within JavaScript, I would suggest that you write stringified JSON to the file. You could then do:

const fs = require('file-system');
const users = [{userId: 123, userPoints: 45, userCodes: [1, 2, 3]}]

fs.writeFile('SavedAccounts.json', JSON.stringify(users), function (err) {
  if (err) {
    console.log("write failed")
  } else {
    console.log("write success")
  }
})

Instead of appending to the file, you would add/remove and alter your array of users, then write the whole thing back to the file.

You would need to JSON.parse() when reading the file back out

If you wanted to update a specific user you could do:

const userId = 123;
const user = users.indexOf(user => user.id === 123);

user.userPoints = 46;

fs.writeFile('SavedAccounts.json', JSON.stringify(users), function (err) {
  if (err) {
    console.log("write failed")
  } else {
    console.log("write success")
  }
})

This should be split up into methods properly, but hopefully explains the idea

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM