I am having trouble getting Angular 6 to work with lowdb

I am currently in the process of developing an Electron app with Angular 6, utilizing lowdb as a local database.

This is all very new to me and I am learning through trial and error. However, I seem to be encountering difficulty resolving the following error:

To incorporate lowdb into my application, I executed the commands:

npm install --save lowdb (edit: forgot to mention I did this already)

and

npm install --save @types/lowdb

I have created a service that interfaces with this "local database".

import { Injectable } from '@angular/core';
import lowdb from 'lowdb';
import { default as FileAsync } from 'lowdb/adapters/FileAsync';
import { CurrentUserModel } from '../models/current-user';

@Injectable({
  providedIn: 'root'
})
export class LowdbService {

  private db: lowdb.LowdbAsync;

  constructor() {
    this.initDatabase();
  }

  set( field: string, value: any ) {
    this.db.set( field, value ).write();
  }

  private async initDatabase() {
    const adapter = new FileAsync( 'db.json' );
    this.db = await lowdb( adapter );

    this.db.defaults( { user: CurrentUserModel } );
  }
}

However, when I include the service in the constructor of a component, I encounter errors.

ERROR in ./src/app/services/lowdb.service.ts
Module not found: Error: Can't resolve 'lowdb' in '/Users/paul/Projects/application-name/src/app/services'
ERROR in ./src/app/services/lowdb.service.ts
Module not found: Error: Can't resolve 'lowdb/adapters/FileAsync' in '/Users/paul/Projects/application-name/src/app/services'
ℹ 「wdm」: Failed to compile.
ERROR in src/app/services/lowdb.service.ts(2,12): error TS1192: Module '"/Users/paul/Projects/application-name/node_modules/@types/lowdb/index"' has no default export.
src/app/services/lowdb.service.ts(3,14): error TS2305: Module '"/Users/paul/Projects/application-name/node_modules/@types/lowdb/adapters/FileAsync"' has no exported member 'default'.

From what I can see, I am following the steps outlined in this Github comment and this Stackoverflow post. Unfortunately, I am unable to locate further documentation on this issue.

Is there anyone who can offer assistance?

Update
By using import * as lowdb from 'lowdb', I was able to resolve my initial errors. However, it led to a few additional errors. See below.

ERROR in ./node_modules/graceful-fs/polyfills.js
Module not found: Error: Can't resolve 'constants' in '/Users/paul/Projects/project-name/node_modules/graceful-fs'
ERROR in ./node_modules/graceful-fs/graceful-fs.js
Module not found: Error: Can't resolve 'fs' in '/Users/paul/Projects/project-name/node_modules/graceful-fs'
ERROR in ./node_modules/graceful-fs/fs.js
Module not found: Error: Can't resolve 'fs' in '/Users/paul/Projects/project-name/node_modules/graceful-fs'
ERROR in ./node_modules/graceful-fs/legacy-streams.js
Module not found: Error: Can't resolve 'stream' in '/Users/paul/Projects/project-name/node_modules/graceful-fs'

Answer №1

If you have only installed the typings for `lowdb` with `@types/lowdb`, you also need to install the actual library using:

npm install --save lowdb

It seems that there is no default export, so importing `lowdb` directly won't work. Try this approach instead:

import { LowdbAsync } from 'lowdb';
import * as lowdb from 'lowdb';
import * as FileAsync from 'lowdb/adapters/FileAsync';

private db: LowdbAsync<any>; // Make sure to specify correct schema here

private async initDatabase() {
  const adapter = new FileAsync('db.json');
  this.db = await lowdb(adapter);

  this.db.defaults({ user: any });
}

Alternatively, you can remove outdated typings and follow the documentation provided by `lowdb`:

https://github.com/typicode/lowdb/tree/master/examples#browser

import low from 'lowdb'
import LocalStorage from 'lowdb/adapters/LocalStorage'

If you encounter other issues, refer to this discussion:

https://github.com/typicode/lowdb/issues/206#issuecomment-324884867

typicode commented on 25 Aug 2017

@DickyKwok I think it's impossible. Can you answer this, @typicode?

I confirm, to save to disk using FileSync or FileAsync adapters you need to have access to Node fs API.

Consider using the `LocalStorage` adapter instead based on their recommendation.

For related queries, check out this thread: How can I use node "fs" in electron within angular 5

You may also explore the solution suggested in one of the answers provided:

https://github.com/ThorstenHans/ngx-electron

constructor(private _electronService: ElectronService) { 
    this.fs = this._electronService.remote.require('fs');
}

Answer №2

Seems like the lowdb module is not present in your node_modules directory.

Please attempt the following:

npm install lowdb

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I display a route from the starting point to the destination with all markers on a Leaflet map, using latitudes and longitudes from an API in Angular

Let's consider a scenario where we have a single bus with a fixed route, and all the bus stops along that route are marked. How can we achieve this in Angular using Leaflet maps as shown in the following image https://i.stack.imgur.com/GgEPS.png ...

What could be causing the initial element of a class returned by Jarray.ToObject to consistently be null, despite the presence of assigned data in the JSON?

Trying to Deserialize data from a public API, like this: [ { "title": "Bitcoin", "symbol": "₿", "rank": 1, "age": 4913, "color": "#fa9e32", "pn ...

Encountering a [object Object] error at the AppComponent_Host ngfactory js file while working on an Angular 8

While attempting to run the official sample angular app provided by Microsoft Identity platform (which utilizes the MSAL library for authenticating Azure AD users), an error is encountered. It seems that there may be a challenge in pinpointing the specific ...

What is the process for integrating a tensorflow.js model into a React-based web application?

I've been working on a React web application in Typescript that involves loading a tensorflow.js model and then applying it each time the component updates. While I successfully implemented this in a small demo app without React, I am facing some chal ...

Enhancing the getDate function in JavaScript with additional days

My function for selecting the date is working perfectly: formatDateField(event: Date, formControl: string) { this.form .get(formControl) .patchValue( this.datePipe.transform(event.getTime(), "yyyy-MM-dd'T'HH:mm:ss&quo ...

Failed to retrieve values from array following the addition of a new element

Does anyone have a solution for this problem? I recently added an element to my array using the push function, but when I tried to access the element at position 3, it wasn't defined properly processInput(inputValue: any): void { this.numOfIma ...

Enhance your UI experience with a beautifully styled button using Material-

I was using a Material UI button with a purple background. <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', heig ...

JS : Removing duplicate elements from an array and replacing them with updated values

I have an array that looks like this: let arr = ['11','44','66','88','77','00','66','11','66'] Within this array, there are duplicate elements: '11' at po ...

Executing JavaScript functions externally from the Angular 6 application

I have a unique scenario where my angular 6 app is embedded within another application that injects JavaScript to the browser to expose specific functionalities to the angular app. For example, when running my angular app within this external application, ...

Obtaining a Bearer token in Angular 2 using a Web

I am currently working on asp.net web api and I am looking for a way to authenticate users using a bearer token. On my login page, I submit the user information and then call my communication service function: submitLogin():void{ this.user = this.l ...

Tips on organizing orders by various cities with Laravel, MySQL, and JSON

I am currently working on generating a report with order-related information from a Laravel project. However, I am facing challenges in determining the specific data structure required for this task. Here is what I need: // Date Ranges $fromDate = $this- ...

Comprehending the concept of TypeScript type assertion

Currently, I'm learning TypeScript and I came across a code snippet that is causing some confusion. var str = '1' var str2:number = <number> <any> str //str is now of type number console.log(typeof(str2)) log: String From m ...

Mastering the art of utilizing Angular Routing alongside CSS grid for seamless website navigation

My <app-root> layout is pretty straightforward: app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.compone ...

Currently, I am working on developing a to-do task manager using Angular 2. One of the tasks I am tackling involves updating the value

I'm facing an issue with managing to-do tasks. I would like to update the value of an option in a select dropdown when the (change) event is triggered. There are 2 components: //app.component.ts //array object this.dataArr[this.counter] = {id: this ...

How to properly pass a parameter value to an Angular service when using inject.get in the constructor

After experimenting with injecting services in Angular, I encountered an issue when trying to call LogService within GlobalErrorHandler. Despite my best efforts, the code below just wouldn't work. I discovered that the problem stemmed from not passin ...

Creating an Angular 2 service that relies on other services, while allowing components to inject only the parent service

In the scenario where a ParentService depends on ChildService, it is important to list both services in the "providers" attribute of the @Component definition. Is there a method to configure ParentService to automatically inject ChildService, simplifying ...

Issue with Angular 12 SSR: Translation file paths are not being properly retrieved

In my Angular project, I have a file located at src->app->lang-translate->lang-translate.module.ts that is trying to access files from other locations as shown below: {prefix: "../../assets/translate/Pages/header/", suffix: ".json"}, {prefix: "../ ...

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

Ensuring the accuracy of POST data received from Swagger JSON schema in a Node.js

When working with a swagger spec, I have defined the schema for the object returned by a GET query. However, if I am dealing with a POST endpoint that includes the same object, can I specify a json.schema for the parameters being POSTed? It would be redund ...

connecting a BehaviorSubject to the [disabled] property of a button

My component has a variable refreshButtonEnabled$ = new BehaviorSubject<boolean>(true); and also a button <button [disabled]="!refreshButtonEnabled$ | async">refresh</button> However, I encountered the following error message: ...