[英]Read Specificst from txt file - javascript
我從變量userId,userPoints和userCodes開始。
我想要一個包含以下內容的文本文件:
[userId:user9283],[userPoints:45],[userCodes:kjsdnosd,sndjncjks,nsdjknckjs]
在javascript中,您將如何使用該格式將收集到的數據寫入txt文件,在變量更改時進行更改,並在需要時僅獲取數組中userCodes的內容。
這有點像數據庫,但是本地存儲少量數據。 我已經研究了fs.WriteFile和AppendFile,但不確定如何讀取行的特定內容和/或添加到特定內容,檢查其中是否已經有userid,如果有,則附加它。
謝謝 :)
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")
如果您打算僅在JavaScript中使用數據,建議您將字符串化的JSON寫入文件。 然后,您可以執行以下操作:
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")
}
})
除了添加到文件外,您還可以添加/刪除和更改用戶數組,然后將整個內容寫回到文件中。
讀回文件時需要JSON.parse()
如果要更新特定用戶,可以執行以下操作:
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")
}
})
應該將其適當地分解為方法,但希望可以解釋這個想法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.