lowdb | Use native JavaScript API | JSON Processing library
kandi X-RAY | lowdb Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
lowdb Key Features
lowdb Examples and Code Snippets
Trending Discussions on lowdb
Trending Discussions on lowdb
QUESTION
I'm using https://github.com/typicode/lowdb for a small project. I need a query which searches multiple records and returns each record it finds as an array.
For example, for a db such as:
"records": [
{
"id": "sadohfdsf",
"username": "user1",
"data": "abc"
},
{
"id": "tiyuykuy",
"username": "user1",
"data": "xyz"
},
{
"id": "tryehhrt",
"username": "user2",
"data": "tyu"
}
]
I'd like to query all the records for username: "user1"
and get all the records for that user in an array.
I've tried the default:
const user = await db.get('records')
.find({ username: "user1" })
.value();
return user;
but it only finds the first record in the db.
What's the correct way to find multiple records in lowdb?
ANSWER
Answered 2022-Mar-03 at 05:20NOTE: I don't use LowDB
Judging by the docs, I think it's not possible to find multiple records in LowDB. Instead, you can use the Array#filter
method.
// Assuming the following returns an array of your object
const users = await db.get('records')
.value();
// We can `filter` the user(s)
const result = users.filter(
user => user.username === 'user1' /* or any other username */
);
QUESTION
I'm importing types from lowdb via @types/lowdb, and when using their mixins()
method to configure mixins on a store, it complains that the argument I'm passing doesn't type-match:
Argument of type 'Map' is not assignable to parameter of type 'Dictionary<(...args: any[]) => any>'. Index signature is missing in type 'Map'.ts(2345)
I assumed that the type accepted by the mixins
method was essentially a map of functions indexed with a string. So figured that Map
would be an acceptable thing to pass it. The context:
async setupStore ({storeName, storeMixins} : {storeName: string, storeMixins: Map}) {
const store: LowdbSync = await lowdb(new StoreMemoryAdapter(storeName))
store._.mixin(storeMixins)
}
I guess my confusion here is a lack of understanding of what Dictionary<(...args: any[]) => any>
expects in real terms. I'm unable to use the type declaration myself as it is not available to me in userland. But perhaps Map
is not the correct equivalent?
ANSWER
Answered 2021-Aug-09 at 12:30The error message is most important here:
Index signature is missing in type 'Map'.ts(2345)
More information about index signatures you can find in the docs
Let's take a look on Map
type definition:
interface Map {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
readonly size: number;
}
As you might have noticed there is no index signature {[prop: string]:any}
This means that it is impossible to do smtg like this: Map[string]
. COnsider this example:
type Fn = (...args: any[]) => any
type A = Map[string] // error
type B = Record[string] // ok -> Fn
interface C {
[prop: string]: Fn
}
type Cc = C[string] // ok -> Fn
Btw, there is a small difference between types an interfaces in context of indexing. Please see this answer.
QUESTION
When trying to run a lowdb example from https://github.com/typicode/lowdb I got the following error message:
SyntaxError: Unexpected token for operation '||='
It fails in the line:
db.data ||= { posts: [] }
I am using nodejs 14.
Thanks
ANSWER
Answered 2021-May-20 at 20:45I am using nodejs 14.
The logical assignment ||=
is not supported in Node.js 14. It's supported starting 15.0.0
See Node.green.
QUESTION
I want to have a lowdb Json database and in it I want to be able to get all the "urls" and list only the 'slug', the 'url', and the 'stats' for each and every single one like this (with JS,HTML)-> (Below is how it should be listed {in HTML, JS})
Slug: Example
Url: https://example.com
Stats: 37
Slug: Example1234
Url: https://example.net
Stats: 15
Slug: Exampleio
Url: https://example.io
Stats: 20
And this is how the database would look:
{
"urls": [
{
"slug": "example",
"url": "https://example.com",
"token": "amazingdev1",
"stats": 37
},
{
"slug": "example1234",
"url": "https://example.net",
"token": "adsfrdmgsrf",
"stats": 15
},
{
"slug": "exampleio",
"url": "https://example.io",
"token": "07dfpwxukck57rv5",
"stats": 20
}
]
}
I am pretty new to all this stuff; how would you do it? Thanks in advance!
ANSWER
Answered 2021-Apr-29 at 01:17I found the answer to my question (Thanks to @ch1ck3n) :
Since db.json looks like this:
{
"urls": [
{
"slug": "example",
"url": "https://example.com",
"token": "ah4ret7w",
"stats": 37
},
{
"slug": "example1234",
"url": "https://example.net",
"token": "adsfrdmgsrf",
"stats": 15
},
{
"slug": "exampleio",
"url": "https://example.io",
"token": "07dfpwxukck57rv5",
"stats": 20
}
]
}
...Then index.js would look like this:
const express = require('express');
const app = express();
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('db.json')
const db = low(adapter)
re = ""
db.get('urls').__wrapped__.urls.forEach(function(item){
re += ""
re += ("Slug: " + item.slug +"
");
re += ("Url: " + item.url+"
")
re += ("Stats: " + item.stats+"
")
re += ""
re += ("
")
});
app.get('/', (req, res) => {
res.send(re)
});
app.listen(3000, () => {
console.log('server started');
});
A working demo is shown here.
QUESTION
I'm wondering if there's someone knowledgeable in Vue(2 or 3)'s reativity that might be able to answer this question and explain reasons.
This is regarding features such as data() reactivity (getters & setters), computed properties, a global Vue instance, and even a Vuex store.
Is there a way I could tap into just these non-browser javascript features for use in a backend-only Node.js application?
I need a way to have a global store holding temporary data that can update "components" in other files via mapState/mapGetters.
I'm using lowdb currently for this because it suits my needs in terms of shapeable JSON objects, where something like redis is key:value-only. (Don't want to get into a more complex redis/rejson setup.)
Basically I need a globally accessible relatively-full-featured reactivity system on the backend, without global variables or needing to set up a custom Rxjs system, which is a bit over my head and will take too much momentum away from my goals, time-wise.
I'd appreciate any input. Thanks 🙂
ANSWER
Answered 2021-Mar-14 at 15:44Vue is designed to run inside Node to support SSR (server side rendering). There is already a good post here on SO with simple sample for Vue 2 (using Vue + Vuex)
But it seems overkill to me. If you want something much simpler and lightweight, you can use package @vue/reactivity which is normally part of the Vue 3 but can be used completely standalone. It is basically Vue 3 reactivity system based on JS proxies
Why would I choose this approach:
- No Vue 2 Change Detection Caveats
- More "functional" API (designed for their new Composition API) with much better support for TypeScript and type inference (even without TS)
- I think Vuex API is super bad (using string constants for data mapping - especially with modules. It's pain...)
As it is part of Vue 3, you can use it's documentation:
QUESTION
I'm using a library (lowdb) that uses lodash under the hood to make a local database in a json file. The thing I want to know is how to get to the parent object in lodash chaining after modifying child to modify another one, eg.
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync('db.json');
const db = low(adapter);
/*
Eg. DB structure:
{
"posts": [
{
"id": 1,
"title": "post1"
},
{
"id": 2,
"title": "post2"
},
{
"id": 3,
"title": "post3"
}
]
}
*/
db
.get('posts')
.find({ id: 2 })
.assign({ title: 'edited title' })
//after that I want to go back to posts to edit another one in the same chain
.write();
I know that it could be done in multiple calls but I was wondering if it's possible to do it in one chain.
ANSWER
Answered 2021-Jan-28 at 00:35If your goal is to make your code as good looking as possible, I would recommend you use lodash-id, and its updateById
function. I introduce all kind of possible solutions in my long answer, but personally I would avoid chaining directly, and instead do something like:
const lodashId = require('lodash-id');
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync('db.json');
const db = low(adapter);
db._.mixin(lodashId);
const posts = db.get("posts");
posts.updateById( 1, { title: 'edited title 1' }).commit();
posts.updateById( 2, { title: 'edited title 2' }).commit();
posts.updateById( 3, { title: 'edited title 3' }).commit();
posts.write();
There are a few ways to approach this problem, and updateById
is not the only way to do it by far. As a matter of fact, it is also possible to do this in one chain by using the tap
function. Below I introduce a few alternatives.
Of course! I actually made a Codepen where you can try all of the different possible approaches directly in your browser, just remember to open your browser console to see the test results! Here is the link: https://codepen.io/jhack_jos/pen/XWNrpqX
How do I call the functions?All those functions receive an adapter as input. You can call them this way:
const result = testcaseXY(adapter);
function testcase1A(adapter)
{
const db = low(adapter);
return db
.get("posts")
.tap( (posts) => _.chain(posts).find({ id: 1 }).assign({ title: 'edited title 1' }).commit())
.tap( (posts) => _.chain(posts).find({ id: 2 }).assign({ title: 'edited title 2' }).commit())
.tap( (posts) => _.chain(posts).find({ id: 3 }).assign({ title: 'edited title 3' }).commit())
.write();
}
What is tap
?
- it's a utility function from lodash
- it does not directly change the database
- it does, however, pass a reference to the object hold to the
interceptor
function (in this example I used an arrow function) - the reference to the value can be changed, thus affecting the object inside the database
- calling
.write()
on the database makes the changes definitive.
function testcase2A(adapter)
{
const db = low(adapter);
_.mixin(lodashId);
return db
.get("posts")
.tap( (posts) => _.chain(posts).find({ id: 1 }).set("title", 'edited title 1').commit())
.tap( (posts) => _.chain(posts).find({ id: 2 }).set("title", 'edited title 2').commit())
.tap( (posts) => _.chain(posts).find({ id: 3 }).set("title", 'edited title 3').commit())
.write();
}
What is set
?
- it's a slightly shorter way to do what
.assign
does, but only with one property. - you may expect
.set
to be faster then.assign
function testcase3A(adapter)
{
const db = low(adapter);
_.mixin(lodashId);
return db
.get("posts")
.tap( (posts) => _.chain(posts).updateById( 1, { title: 'edited title 1' }).commit())
.tap( (posts) => _.chain(posts).updateById( 2, { title: 'edited title 2' }).commit())
.tap( (posts) => _.chain(posts).updateById( 3, { title: 'edited title 3' }).commit())
.write();
}
What is updateById
?
- it's a function that is exposed by the lodash-id library
- you must first add it to lowdb as a mixin
- to do so you first need to require it with
const lodashId = require('lodash-id')
- then you need to call
db._.mixin(lodashId)
; - here instead I am calling directly
_.mixin(lodashId)
, because I am directly using lodash inside thetap
function, without going through lowdb
function testcase1B(adapter)
{
const db = low(adapter);
const posts = db.get("posts");
posts.find({ id: 1 }).assign({ title: 'edited title 1' }).commit();
posts.find({ id: 2 }).assign({ title: 'edited title 2' }).commit();
posts.find({ id: 3 }).assign({ title: 'edited title 3' }).commit();
return posts.write();
}
As you may see, using a temporary variable here gives us a more compact code, which could be easier to read, debug, and refactor.
2B) temporary variable & find+setfunction testcase2B(adapter)
{
const db = low(adapter);
const posts = db.get("posts");
posts.find({ id: 1 }).set("title", 'edited title 1').commit();
posts.find({ id: 2 }).set("title", 'edited title 2').commit();
posts.find({ id: 3 }).set("title", 'edited title 3').commit();
return posts.write();
}
function testcase3B(adapter)
{
const db = low(adapter);
db._.mixin(lodashId);
const posts = db.get("posts");
posts.updateById( 1, { title: 'edited title 1' }).commit();
posts.updateById( 2, { title: 'edited title 2' }).commit();
posts.updateById( 3, { title: 'edited title 3' }).commit();
return posts.write();
}
I'd be glad to give any further explanation, may you need it. As a bonus I would add it could be possible to write some clever utility function as a lowdb/lodash mixin in order to enable us to have a shorter syntax and still properly chain. That is, however, probably more than what you were looking for.
QUESTION
// LocalStorage is a lowdb adapter for saving to localStorage
const adapter = new LocalStorage('db')
// Create database instance
const db = low(adapter)
// Set default state
db.defaults({ items: [] })
.write()
Now how it can be saved where it's hosted like in './maindb.json'
? Is there anything available like FileSync?
Update
after realising there no way that client can access server filesystem. I probably asked a wrong question. but there is a solution using fetch. so if anyone has ans please put it down I am trying my best.
index.html -> fetch(jsonObj) -> post -> save.php-> creates maindb.json/updates.
index.html -> fetch() -> get -> save.php -> returns from maindb.json.
ANSWER
Answered 2020-Dec-01 at 06:18Controller.php
init();
}
private function init(){
if (!file_exists($this->file)) {
touch($this->file);
$this->read();
}else{
$this->read();
}
}
private function read(){
$this->jsondata = file_get_contents($this->file);
$this->tempArray = $this->jsondata != null ? json_decode($this->jsondata): array();
}
private function write(){
array_push($this->tempArray, $this->data);
$this->jsondata = json_encode($this->tempArray);
file_put_contents($this->file, $this->jsondata);
}
public function push($data){
$this->data = $data;
if($this->data){
$this->write();
return true;
}
}
public function get(){
$this->read();
return json_encode($this->tempArray);
}
}
?>
json.php
push($_POST['data'])){
echo $db->get();
}
?>
javascript
function post(input){
var data = {'data': input}
$.ajax({
type: 'POST',
url: 'json.php',
dataType: 'json',
data: data,
success: function(data) {
console.log(data)
}
});
}
QUESTION
I make a lowdb request to update a JSON file, but only the date is updated. When I make a console.log of the information to update, this is what I want to update:
res.on("end", function () {
let body = Buffer.concat(chunks);
let final = JSON.parse(body);
if (final.error !== undefined) {
console.log("Initial authentication:", final.error_description, "Please refresh the authentication grant");
extAuthCallback(84);
} else {
tokens.set('access_token', final.access_token)
.set('expires_in', final.expires_in)
.set('refresh_token', final.refresh_token)
.set('refresh_date', moment())
.write()
console.log(final, tokens.value())
extAuthCallback(1);
}
});
console.log of my final variable:
{
access_token: 'oa_prod_iq00cRPk5Jhh4VffSHlDj7DEDsSIlpCRRczI3l3ASC0',
token_type: 'bearer',
expires_in: 2399,
refresh_token: 'oa_prod_nIjBZs74xGvJXi1B-wdMyITfxGyklpCRRczI3l3ASC0'
}
console.log of my JSON file after the request:
{
access_token: 'oa_prod_pB9Q0FFM9Tk4c5n3HMRBFKAVz6naiJ-jmb3QCeBrT00',
expires_in: 2399,
refresh_token: 'oa_prod_nX3EDs530SM8eHv_fM5BN7-5RLBwkrKoUi6uExBbTY4',
refresh_date: '2020-11-28T23:31:13.855Z',
primary_autorization_date: '2020-11-29T00:40:58.421Z'
}
My JSON file after the modifications:
{
"access_token": "oa_prod_pB9Q0FFM9Tk4c5n3HMRBFKAVz6naiJ-jmb3QCeBrT00",
"expires_in": 2399,
"refresh_token": "oa_prod_nX3EDs530SM8eHv_fM5BN7-5RLBwkrKoUi6uExBbTY4",
"refresh_date": "2020-11-28T23:31:13.855Z",
"primary_autorization_date": "2020-11-29T00:40:58.421Z"
}
So it only has the primary_autorization_date
field changing...
ANSWER
Answered 2020-Nov-29 at 13:33You should use set
instead of update
.
tokens.set('access_token', final.access_token)
.set('expires_in', final.expires_in)
.set('refresh_token', final.refresh_token)
.set('refresh_date', moment())
.write()
The update method is accepted a function like this.
db.update('test1', (n) => 5555)
.update('test2', (n) => n + 1)
.write()
If you use set
, you just need to assign the value to it.
db.set('test1', 5555).set('test2', 3333).write()
And when you use moment
, there are two ways to you could use.
// Way 1 with moment()
db.set('date', moment()).write()
// Way 2 with moment
db.update('date', moment).write()
QUESTION
I'm getting this error : Cannot read property match
of undefined.
Cannot read property 'match' of undefined
This is the line in polyfills.js pointed by the error message:
I do not have any clue about this kind of problem, because it doesn't point to any specific file. Would you be so kind in having a look at this github repo.
https://github.com/raphael10-collab/ElectronVueTypeScriptScaffolding
Update 1)
Thanks to Elias comment, I realized that vue.config.js was messed-up. Now vue.config.is is :
// https://nklayman.github.io/vue-cli-plugin-electron-builder/guide
/guide.html#web-workers
const WorkerPlugin = require('worker-plugin')
module.exports = {
// options...
publicPath: '',
pluginOptions: {
electronBuilder: {
// Prevent bundling of certain imported packages and instead
retrieve these external dependencies at runtime.
// In order to connect to websocket.
externals: ['ggc'],
builderOptions: {
productName: 'GGC',
win: {
icon: './public/app.ico'
},
mac: {
icon: './public/icons/Icon.icns',
target: [
'pkg',
'dmg',
'zip',
],
},
linux: {
icon: './public/app.png'
}
},
// https://nklayman.github.io/vue-cli-plugin-electron-builder
/guide/configuration.html#webpack-configuration
chainWebpackRendererProcess: (config) => {
// Chain webpack config for electron renderer process only
// The following example will set IS_ELECTRON to true in your
app
config.plugin('define').tap((args) => {
args[0]['IS_ELECTRON'] = true
return args
})
},
mainProcessFile: 'src/background.js',
// https://nklayman.github.io/vue-cli-plugin-electron-builder
/guide/configuration.html#typescript-options
disableMainProcessTypescript: false, // Manually disable
typescript plugin for main process. Enable if you want to use regular
js for the main process (src/background.js by default)
mainProcessTypeChecking: false, // Manually enable type checking
during webpck bundling for background file.
// https://nklayman.github.io/vue-cli-plugin-electron-builder
/guide/guide.html#preload-files
preload: 'src/preload.js',
// https://nklayman.github.io/vue-cli-plugin-electron-builder
/guide/security.html#node-integration
nodeIntegration: true
},
// https://nklayman.github.io/vue-cli-plugin-electron-builder
/guide/guide.html#web-workers
configureWebpack: {
plugins: [new WorkerPlugin()]
}
}
}
Regarding nodeIntegration, I disabled it in /src/background.js because I read it is more secure to have preload.js file
This is my new webpack.config.js (it was messed up as well, like vue.config.is, with each module.exports overriding the previous one):
module.exports = {
entry: './src/background.js',
target: 'node',
output: {
path: path.join(__dirname, 'build'),
filename: 'background.js'
},
// https://github.com/GoogleChromeLabs/worker-plugin
plugins: [
new WorkerPlugin()
]
}
I do not understand what should I enable here in webpack: https://webpack.js.org/plugins/define-plugin/
Update 2)
I disabled nodeIntegration in vue.config.js
vue.config.js :
// https://nklayman.github.io/vue-cli-plugin-electron-builder/guide
/guide.html#web-workers
const WorkerPlugin = require('worker-plugin')
module.exports = {
// options...
publicPath: '',
pluginOptions: {
electronBuilder: {
// Prevent bundling of certain imported packages and instead
retrieve these external dependencies at runtime.
// In order to connect to websocket.
externals: ['ggc'],
builderOptions: {
productName: 'GGC',
win: {
icon: './public/app.ico'
},
mac: {
icon: './public/icons/Icon.icns',
target: [
'pkg',
'dmg',
'zip',
],
},
linux: {
icon: './public/app.png'
}
},
// https://nklayman.github.io/vue-cli-plugin-electron-builder
/guide/configuration.html#webpack-configuration
chainWebpackRendererProcess: (config) => {
// Chain webpack config for electron renderer process only
// The following example will set IS_ELECTRON to true in your
app
config.plugin('define').tap((args) => {
args[0]['IS_ELECTRON'] = true
return args
})
},
mainProcessFile: 'src/background.js',
// https://nklayman.github.io/vue-cli-plugin-electron-builder
/guide/configuration.html#typescript-options
disableMainProcessTypescript: false, // Manually disable
typescript plugin for main process. Enable if you want to use regular
js for the main process (src/background.js by default)
mainProcessTypeChecking: false, // Manually enable type checking
during webpck bundling for background file.
// https://nklayman.github.io/vue-cli-plugin-electron-builder
/guide/guide.html#preload-files
preload: 'src/preload.js',
// https://nklayman.github.io/vue-cli-plugin-electron-builder
/guide/security.html#node-integration
nodeIntegration: false
},
// https://nklayman.github.io/vue-cli-plugin-electron-builder
/guide/guide.html#web-workers
configureWebpack: {
plugins: [new WorkerPlugin()]
}
}
}
and defined process in webpack.config.js
webpack.config.js :
module.exports = {
entry: './src/background.ts',
target: 'node',
output: {
path: path.join(__dirname, 'build'),
filename: 'background.js'
},
// https://github.com/GoogleChromeLabs/worker-plugin
plugins: [
new WorkerPlugin()
],
// https://webpack.js.org/plugins/define-plugin/
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
}
When running yarn electron:serve I now get Error: Cannot read property 'match' of undefined
If I keep nodeIntegration:true in vue.config.js and change in src/background.js to :
webPreferences: {
nodeIntegration: true,
//nodeIntegration: false,
//contextIsolation: true, // protects against prototype pollution
//preload: path.join(__dirname, "../dist_electron/preload.js"),
},
when running yarn electron:serve I get this error: "Cannot read property 'app' of undefined"
This is /src/store/modules/app.ts :
import Vue from 'vue'
import { loadSettings, setSettings } from '@/services/electron-
services/setting/setting'
const TOGGLE_THEME = 'TOGGLE_THEME'
const stateRecord: App = loadSettings()
const app = {
state: {
currentTheme: stateRecord.currentTheme || 'light',
},
mutations: {
[TOGGLE_THEME](state: App, currentTheme: Theme) {
state.currentTheme = currentTheme
},
},
actions: {
TOGGLE_THEME({ commit }: any, payload: App) {
setSettings('settings.currentTheme', payload.currentTheme)
commit(TOGGLE_THEME, payload.currentTheme)
},
},
}
export default app
But I would prefer to solve the problem while keeping nodeIntegration: false in order to keep the app safer
Update 3) I discovered that the problem "Cannot read property match
of undefined" disappears once I comment this line
const theme = db.get('settings.currentTheme');
in src/background.ts :
async function create Window() {
const windowSize = db.get('windowSize');
//const theme = db.get('settings.currentTheme');
win = new BrowserWindow({
...windowSize,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, "../dist_electron/preload.js"),
},
})
and db.get('settings.currentTheme') comes from this file:
src/services/electron-services/database/index.ts :
import Lowdb from 'lowdb'
import FileSync from 'lowdb/adapters/FileSync'
import path from 'path'
import fs from 'fs-extra'
import LodashID from 'lodash-id'
import { app, remote } from 'electron'
interface Schema {
windowSize: {
height: number
width: number
}
settings: {
currentLang: string
currentTheme: string
}
}
const isRenderer: boolean = process.type === 'renderer'
// Render process use remote app
const APP: Electron.App = isRenderer ? remote.app : app
const STORE_PATH: string = APP.getPath('userData')
// In production mode, during the first open application
// APP.getPath('userData') gets the path nested and the datastore.js
is loaded.
// if it doesn't exist, create it.
if (!isRenderer) {
if (!fs.pathExistsSync(STORE_PATH)) {
fs.mkdirpSync(STORE_PATH)
}
}
class DB {
private db: Lowdb.LowdbSync
public constructor() {
const adapter: Lowdb.AdapterSync = new FileSync
(path.join(STORE_PATH, '/db.json'))
this.db = Lowdb(adapter)
// Use lodash-id must use insert methods
this.db._.mixin(LodashID)
if (!this.db.has('windowSize').value()) {
this.db
.set('windowSize', {
width: 1025,
height: 749,
})
.write()
}
if (!this.db.has('settings').value()) {
this.db
.set('settings', {
//currentLang: 'en',
currentTheme: 'light',
})
.write()
}
// Purple to Night
if (this.db.get('settings.currentTheme').value() === 'purple') {
this.db.set('settings.currentTheme', 'night').write()
}
if (!this.db.has('settings.currentLang')) {
this.db.set('settings.currentLang', 'en').write()
}
}
// read() is to keep the data of the main process and the
rendering process up to date.
public read() {
return this.db.read()
}
public get(key: string): T {
return this.read().get(key).value()
}
public find(key: string, id: string): T {
const data: $TSFixed = this.read().get(key)
return data.find({ id }).value()
}
public set(key: string, value: T): T {
return this.read().set(key, value).write()
}
public insert(key: string, value: T): T {
const data: $TSFixed = this.read().get(key)
return data.insert(value).write()
}
public update(key: string, id: string, value: T): T {
const data: $TSFixed = this.read().get(key)
return data.find({ id }).assign(value).write()
}
public remove(key: string, id: string): T {
const data: $TSFixed = this.read().get(key)
return data.removeById(id).write()
}
public filter(key: string, query: K): T {
const data: $TSFixed = this.read().get(key)
return data.filter(query).value()
}
public has(key: string): boolean {
return this.read().has(key).value()
}
}
export default new DB()
ANSWER
Answered 2020-Aug-30 at 06:22Your problem is the vue.config.js only exports the last object, each module.exports
overrides previous exports.
The other problem you may have is that you disabled nodeIntegration
, thus process
will indeed be undefined
unless you enable webpacks definition.
Edit: To make require
available on the renderer, you need to enable nodeIntegration
in your background.ts file or disable it in vue.config.js.
QUESTION
I'm doing a Discord bot with command handling, but on a file, I can't get the content of my JSON file out with lowdb... I proceed exactly the same way with success in the other files, I don't understand... Here is my code:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('../db.json')
const db = low(adapter)
const adapter2 = new FileSync('../users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;
module.exports = {
name: 'rent',
description: 'Rent a number',
usage: '',
guildOnly: true,
async execute(message, args) {
return console.log(db.get().value())
...
Here's my db.json:
{
"numbers": [
{
"test": "1234"
}
]
}
When I console.log db alone, it takes me out the object, but as soon as I try to console.log with lowdb like above it takes me out undefined ....
ANSWER
Answered 2020-Aug-30 at 01:51So I'm not sure why, but you have to remove a point on the road to lowdb files.
Code not working:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('../db.json')
const db = low(adapter)
const adapter2 = new FileSync('../users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;
Code after modification and functional:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('./db.json')
const db = low(adapter)
const adapter2 = new FileSync('./users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install lowdb
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page