Persist nedb to disk in Electron renderer process (Webpack/Electron/nedb configuration problem)NEDB persistance in Electron apprequire vm2 using electron and webpackHow to use webpack with sequelize?Electron Nedb findOne returns null?Configuring electron-webpack renderer to work with nodeIntegration: falsePrevent emitting certain code when using webpack to deploy Electron app for the webCan't use vue component in my Rails5 appangular-cli.json create error while adding style.cssRequire not defined in script tagError setting up vscode debugging for electron: cannot connect to runtime process and cannot connect to target

Has Rey's new lightsaber been seen before in canon or legends?

To which airspace does the border of two adjacent airspaces belong to?

What is this red bug infesting some trees in southern Germany?

Why didn't Thatcher give Hong Kong to Taiwan?

Is there any difference between these two sentences? (Adverbs)

What is hot spotting in the context of adding files to tempdb?

Generate points for smooth movement between two given points

How could a planet have one hemisphere way warmer than the other without the planet being tidally locked?

Does the Scrying spell require you to have a clear path to the target in order to work?

If I have an accident, should I file a claim with my car insurance company?

Is torque as fundamental a concept as force?

How to encode a class with 24,000 categories?

My boss says "This will help us better view the utilization of your services." Does this mean my job is ending in this organisation?

Can there be plants on the dark side of a tidally locked world?

What happens when there is no available physical memory left for SQL Server?

Does POSIX guarantee the paths to any standard utilities?

Splitting polygons at narrowest part using R?

When is it legal to castle moving the rook first?

Go for an isolated pawn

First Number to Contain Each Letter

Which is the best password hashing algorithm in .NET Core?

If p-value is exactly 1 (1.0000000), what are the confidence interval limits?

Are treasury bonds more liquid than USD?

Was "The Hobbit" ever abridged?



Persist nedb to disk in Electron renderer process (Webpack/Electron/nedb configuration problem)


NEDB persistance in Electron apprequire vm2 using electron and webpackHow to use webpack with sequelize?Electron Nedb findOne returns null?Configuring electron-webpack renderer to work with nodeIntegration: falsePrevent emitting certain code when using webpack to deploy Electron app for the webCan't use vue component in my Rails5 appangular-cli.json create error while adding style.cssRequire not defined in script tagError setting up vscode debugging for electron: cannot connect to runtime process and cannot connect to target






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








5















Problem



I'm trying to use a pure-JS database called nedb in an Electron renderer process. It uses the browser field in its package.json to swap in a browser-based storage system. This is causing my database to not actually be persisted to file.



Background



I'm using Next.js as my view framework, and its Webpack is configured for "target": "electron-renderer" for the rendering thread. Which apparently causes Webpack to process those browser directives, even though renderer processes should have access to both browser and Node APIs. This behavior isn't really documented, so I don't know how to override it.



What I have tried



I have confirmed that if I manually edit out the browser field on the local copy of node_modules/nedb/package.json, the problem goes away.



As a temporary workaround, I've pointed to my own fork of nedb that does this. But this is pretty unsatisfactory.



Other research



Curiously, this doesn't seem to be an issue for electron-vue, whose docs explicitly demonstrate use of nedb from a renderer process. That framework does, indeed, appear to use "target": "electron-renderer" in its Webpack config.



Is there a solution to this problem, perhaps by Webpack configuration?










share|improve this question


























  • Do you have some code that we can look at?

    – customcommander
    Apr 5 at 19:48











  • @customcommander As far as I can tell, the problem happens if you make an Electron project that attempts to instantiate an nedb datastore from a renderer process. I think the issue really comes down to the fact that neither Webpack nor nedb foresaw the existence of a browser environment with file access through Node. Any suggestion on what would be most helpful from a sample code perspective? In my mind, a whole sample project seems like overkill, because we're really talking about scattered config entries.

    – acjay
    Apr 5 at 21:06











  • Fair enough. I’ll have a look.

    – customcommander
    Apr 6 at 7:10

















5















Problem



I'm trying to use a pure-JS database called nedb in an Electron renderer process. It uses the browser field in its package.json to swap in a browser-based storage system. This is causing my database to not actually be persisted to file.



Background



I'm using Next.js as my view framework, and its Webpack is configured for "target": "electron-renderer" for the rendering thread. Which apparently causes Webpack to process those browser directives, even though renderer processes should have access to both browser and Node APIs. This behavior isn't really documented, so I don't know how to override it.



What I have tried



I have confirmed that if I manually edit out the browser field on the local copy of node_modules/nedb/package.json, the problem goes away.



As a temporary workaround, I've pointed to my own fork of nedb that does this. But this is pretty unsatisfactory.



Other research



Curiously, this doesn't seem to be an issue for electron-vue, whose docs explicitly demonstrate use of nedb from a renderer process. That framework does, indeed, appear to use "target": "electron-renderer" in its Webpack config.



Is there a solution to this problem, perhaps by Webpack configuration?










share|improve this question


























  • Do you have some code that we can look at?

    – customcommander
    Apr 5 at 19:48











  • @customcommander As far as I can tell, the problem happens if you make an Electron project that attempts to instantiate an nedb datastore from a renderer process. I think the issue really comes down to the fact that neither Webpack nor nedb foresaw the existence of a browser environment with file access through Node. Any suggestion on what would be most helpful from a sample code perspective? In my mind, a whole sample project seems like overkill, because we're really talking about scattered config entries.

    – acjay
    Apr 5 at 21:06











  • Fair enough. I’ll have a look.

    – customcommander
    Apr 6 at 7:10













5












5








5








Problem



I'm trying to use a pure-JS database called nedb in an Electron renderer process. It uses the browser field in its package.json to swap in a browser-based storage system. This is causing my database to not actually be persisted to file.



Background



I'm using Next.js as my view framework, and its Webpack is configured for "target": "electron-renderer" for the rendering thread. Which apparently causes Webpack to process those browser directives, even though renderer processes should have access to both browser and Node APIs. This behavior isn't really documented, so I don't know how to override it.



What I have tried



I have confirmed that if I manually edit out the browser field on the local copy of node_modules/nedb/package.json, the problem goes away.



As a temporary workaround, I've pointed to my own fork of nedb that does this. But this is pretty unsatisfactory.



Other research



Curiously, this doesn't seem to be an issue for electron-vue, whose docs explicitly demonstrate use of nedb from a renderer process. That framework does, indeed, appear to use "target": "electron-renderer" in its Webpack config.



Is there a solution to this problem, perhaps by Webpack configuration?










share|improve this question
















Problem



I'm trying to use a pure-JS database called nedb in an Electron renderer process. It uses the browser field in its package.json to swap in a browser-based storage system. This is causing my database to not actually be persisted to file.



Background



I'm using Next.js as my view framework, and its Webpack is configured for "target": "electron-renderer" for the rendering thread. Which apparently causes Webpack to process those browser directives, even though renderer processes should have access to both browser and Node APIs. This behavior isn't really documented, so I don't know how to override it.



What I have tried



I have confirmed that if I manually edit out the browser field on the local copy of node_modules/nedb/package.json, the problem goes away.



As a temporary workaround, I've pointed to my own fork of nedb that does this. But this is pretty unsatisfactory.



Other research



Curiously, this doesn't seem to be an issue for electron-vue, whose docs explicitly demonstrate use of nedb from a renderer process. That framework does, indeed, appear to use "target": "electron-renderer" in its Webpack config.



Is there a solution to this problem, perhaps by Webpack configuration?







javascript webpack electron next.js nedb






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 5 at 19:43









customcommander

4,1171 gold badge14 silver badges34 bronze badges




4,1171 gold badge14 silver badges34 bronze badges










asked Mar 28 at 3:19









acjayacjay

19.8k4 gold badges45 silver badges86 bronze badges




19.8k4 gold badges45 silver badges86 bronze badges















  • Do you have some code that we can look at?

    – customcommander
    Apr 5 at 19:48











  • @customcommander As far as I can tell, the problem happens if you make an Electron project that attempts to instantiate an nedb datastore from a renderer process. I think the issue really comes down to the fact that neither Webpack nor nedb foresaw the existence of a browser environment with file access through Node. Any suggestion on what would be most helpful from a sample code perspective? In my mind, a whole sample project seems like overkill, because we're really talking about scattered config entries.

    – acjay
    Apr 5 at 21:06











  • Fair enough. I’ll have a look.

    – customcommander
    Apr 6 at 7:10

















  • Do you have some code that we can look at?

    – customcommander
    Apr 5 at 19:48











  • @customcommander As far as I can tell, the problem happens if you make an Electron project that attempts to instantiate an nedb datastore from a renderer process. I think the issue really comes down to the fact that neither Webpack nor nedb foresaw the existence of a browser environment with file access through Node. Any suggestion on what would be most helpful from a sample code perspective? In my mind, a whole sample project seems like overkill, because we're really talking about scattered config entries.

    – acjay
    Apr 5 at 21:06











  • Fair enough. I’ll have a look.

    – customcommander
    Apr 6 at 7:10
















Do you have some code that we can look at?

– customcommander
Apr 5 at 19:48





Do you have some code that we can look at?

– customcommander
Apr 5 at 19:48













@customcommander As far as I can tell, the problem happens if you make an Electron project that attempts to instantiate an nedb datastore from a renderer process. I think the issue really comes down to the fact that neither Webpack nor nedb foresaw the existence of a browser environment with file access through Node. Any suggestion on what would be most helpful from a sample code perspective? In my mind, a whole sample project seems like overkill, because we're really talking about scattered config entries.

– acjay
Apr 5 at 21:06





@customcommander As far as I can tell, the problem happens if you make an Electron project that attempts to instantiate an nedb datastore from a renderer process. I think the issue really comes down to the fact that neither Webpack nor nedb foresaw the existence of a browser environment with file access through Node. Any suggestion on what would be most helpful from a sample code perspective? In my mind, a whole sample project seems like overkill, because we're really talking about scattered config entries.

– acjay
Apr 5 at 21:06













Fair enough. I’ll have a look.

– customcommander
Apr 6 at 7:10





Fair enough. I’ll have a look.

– customcommander
Apr 6 at 7:10












2 Answers
2






active

oldest

votes


















1







+200









As you stated in your question and per this Github issue on the nedb package the root cause of your issue is that webpack's file resolution process reads the package.browser key in order to alias specific file paths to a different location when the target build is browser or some other value that will cause it to inspect the package.browser property.



electron-vue appears to sidestep the webpack bundling issue by treating all NPM dependencies as externals so that they don't get pulled into the application bundle and instead are expected to be defined on global by some other means. You could similarly designate nedb as an external in your webpack config and pull the Node version into your application via script tag or defining a reference to it on global some other way.



Another solution would be to create a webpack resolver plugin to override how the problematic requires for "./lib/customUtils.js" and "./lib/storage.js" get resolved, bypassing the resolution step that inspects package.browser for aliases for those file paths.



See the webpack documentation for how to pass a custom resolver plugin in your Webpack config. See the wepback/enhanced-resolve documentation for additional details on how plugins are defined and how they work.



Essentially, a plugin is an object with an apply method that takes a resolver instance and performs some step of the file resolution process. In the example below, we test to see whether the current file being resolved is in the nedb package and whether it's one of the two problematic browser aliases. If so, we exit the resolution process with the correct paths to the files. Otherwise we do nothing and defer to the normal resolution process.



// Prevents nedb from substituting browser storage when running from the
// Electron renderer thread.
const fixNedbForElectronRenderer =
apply(resolver)
resolver
// Plug in after the description file (package.json) has been
// identified for the import, which makes sure we're not getting
// mixed up with a different package.
.getHook("beforeDescribed-relative")
.tapAsync(
"FixNedbForElectronRenderer",
(request, resolveContext, callback) =>
// When a require/import matches the target files, we
// short-circuit the Webpack resolution process by calling the
// callback with the finalized request object -- meaning that
// the `path` is pointing at the file that should be imported.
const isNedbImport = request.descriptionFileData["name"] === "nedb"

if (isNedbImport && /storage(.js)?/.test(request.path))
const newRequest = Object.assign(, request,
path: resolver.join(
request.descriptionFileRoot,
"lib/storage.js"
)
)
callback(null, newRequest)
else if (
isNedbImport &&
/customUtils(.js)?/.test(request.path)
)
const newRequest = Object.assign(, request,
path: resolver.join(
request.descriptionFileRoot,
"lib/customUtils.js"
)
)
callback(null, newRequest)
else
// Calling `callback` with no parameters proceeds with the
// normal resolution process.
return callback()


)



// Register the resolver plugin in the webpack config
const config =
resolve:
plugins: [fixNedbForElectronRenderer]







share|improve this answer
































    4
















    You don't need to run the database on the renderer process, instead of that you could run other database that you would like, like sql, sqlite, mongodb, etc, on main process.



    If you don't mind switching database, here is how you could achieve this. In Electron exist a class callled ipcMain and ipcRenderer, this classes are used to make renderer process and main process comunicate. You can send/receive any type of data with ipc.



    Here is an example:



    Renderer.js



    const btnSave = document.getElementById('btn-save')

    // Get any data from forms, etc


    btn.addEventListener('click', () =>
    // ipcRender sends the data via 'receive-data-to-save-in-database' channel, you
    // you can send any type of data, and have has many args you want. In this case I
    // sent a a empty object
    ipcRenderer.send('receive-data-to-save-in-database', )
    )


    Main.js



    // ipcMain listens to channel 'receive-data-to-save-in-database'
    ipcMain.on('receive-data-to-save-in-database', (event, args) =>
    // Code to save in database
    // The empty object will be received in args parameter
    )


    It's not what you wanted, but is a workaround.



    For more information, I suggest you go:



    ipcRenderer Docs
    ipcMain Docs






    share|improve this answer




















    • 2





      Thanks for the thoughts! My understanding is that it's actually not so good to run things like databases on the main process (see medium.freecodecamp.org/… and github.com/louischatriot/nedb/issues/531#issuecomment-477769752). I'm also looking to keep things simple from a debugging standpoint by staying on one thread while I develop my prototype. Lastly, I prefer nedb because it is pure JS.

      – acjay
      Apr 2 at 11:22













    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55389659%2fpersist-nedb-to-disk-in-electron-renderer-process-webpack-electron-nedb-configu%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1







    +200









    As you stated in your question and per this Github issue on the nedb package the root cause of your issue is that webpack's file resolution process reads the package.browser key in order to alias specific file paths to a different location when the target build is browser or some other value that will cause it to inspect the package.browser property.



    electron-vue appears to sidestep the webpack bundling issue by treating all NPM dependencies as externals so that they don't get pulled into the application bundle and instead are expected to be defined on global by some other means. You could similarly designate nedb as an external in your webpack config and pull the Node version into your application via script tag or defining a reference to it on global some other way.



    Another solution would be to create a webpack resolver plugin to override how the problematic requires for "./lib/customUtils.js" and "./lib/storage.js" get resolved, bypassing the resolution step that inspects package.browser for aliases for those file paths.



    See the webpack documentation for how to pass a custom resolver plugin in your Webpack config. See the wepback/enhanced-resolve documentation for additional details on how plugins are defined and how they work.



    Essentially, a plugin is an object with an apply method that takes a resolver instance and performs some step of the file resolution process. In the example below, we test to see whether the current file being resolved is in the nedb package and whether it's one of the two problematic browser aliases. If so, we exit the resolution process with the correct paths to the files. Otherwise we do nothing and defer to the normal resolution process.



    // Prevents nedb from substituting browser storage when running from the
    // Electron renderer thread.
    const fixNedbForElectronRenderer =
    apply(resolver)
    resolver
    // Plug in after the description file (package.json) has been
    // identified for the import, which makes sure we're not getting
    // mixed up with a different package.
    .getHook("beforeDescribed-relative")
    .tapAsync(
    "FixNedbForElectronRenderer",
    (request, resolveContext, callback) =>
    // When a require/import matches the target files, we
    // short-circuit the Webpack resolution process by calling the
    // callback with the finalized request object -- meaning that
    // the `path` is pointing at the file that should be imported.
    const isNedbImport = request.descriptionFileData["name"] === "nedb"

    if (isNedbImport && /storage(.js)?/.test(request.path))
    const newRequest = Object.assign(, request,
    path: resolver.join(
    request.descriptionFileRoot,
    "lib/storage.js"
    )
    )
    callback(null, newRequest)
    else if (
    isNedbImport &&
    /customUtils(.js)?/.test(request.path)
    )
    const newRequest = Object.assign(, request,
    path: resolver.join(
    request.descriptionFileRoot,
    "lib/customUtils.js"
    )
    )
    callback(null, newRequest)
    else
    // Calling `callback` with no parameters proceeds with the
    // normal resolution process.
    return callback()


    )



    // Register the resolver plugin in the webpack config
    const config =
    resolve:
    plugins: [fixNedbForElectronRenderer]







    share|improve this answer





























      1







      +200









      As you stated in your question and per this Github issue on the nedb package the root cause of your issue is that webpack's file resolution process reads the package.browser key in order to alias specific file paths to a different location when the target build is browser or some other value that will cause it to inspect the package.browser property.



      electron-vue appears to sidestep the webpack bundling issue by treating all NPM dependencies as externals so that they don't get pulled into the application bundle and instead are expected to be defined on global by some other means. You could similarly designate nedb as an external in your webpack config and pull the Node version into your application via script tag or defining a reference to it on global some other way.



      Another solution would be to create a webpack resolver plugin to override how the problematic requires for "./lib/customUtils.js" and "./lib/storage.js" get resolved, bypassing the resolution step that inspects package.browser for aliases for those file paths.



      See the webpack documentation for how to pass a custom resolver plugin in your Webpack config. See the wepback/enhanced-resolve documentation for additional details on how plugins are defined and how they work.



      Essentially, a plugin is an object with an apply method that takes a resolver instance and performs some step of the file resolution process. In the example below, we test to see whether the current file being resolved is in the nedb package and whether it's one of the two problematic browser aliases. If so, we exit the resolution process with the correct paths to the files. Otherwise we do nothing and defer to the normal resolution process.



      // Prevents nedb from substituting browser storage when running from the
      // Electron renderer thread.
      const fixNedbForElectronRenderer =
      apply(resolver)
      resolver
      // Plug in after the description file (package.json) has been
      // identified for the import, which makes sure we're not getting
      // mixed up with a different package.
      .getHook("beforeDescribed-relative")
      .tapAsync(
      "FixNedbForElectronRenderer",
      (request, resolveContext, callback) =>
      // When a require/import matches the target files, we
      // short-circuit the Webpack resolution process by calling the
      // callback with the finalized request object -- meaning that
      // the `path` is pointing at the file that should be imported.
      const isNedbImport = request.descriptionFileData["name"] === "nedb"

      if (isNedbImport && /storage(.js)?/.test(request.path))
      const newRequest = Object.assign(, request,
      path: resolver.join(
      request.descriptionFileRoot,
      "lib/storage.js"
      )
      )
      callback(null, newRequest)
      else if (
      isNedbImport &&
      /customUtils(.js)?/.test(request.path)
      )
      const newRequest = Object.assign(, request,
      path: resolver.join(
      request.descriptionFileRoot,
      "lib/customUtils.js"
      )
      )
      callback(null, newRequest)
      else
      // Calling `callback` with no parameters proceeds with the
      // normal resolution process.
      return callback()


      )



      // Register the resolver plugin in the webpack config
      const config =
      resolve:
      plugins: [fixNedbForElectronRenderer]







      share|improve this answer



























        1







        +200







        1







        +200



        1






        +200





        As you stated in your question and per this Github issue on the nedb package the root cause of your issue is that webpack's file resolution process reads the package.browser key in order to alias specific file paths to a different location when the target build is browser or some other value that will cause it to inspect the package.browser property.



        electron-vue appears to sidestep the webpack bundling issue by treating all NPM dependencies as externals so that they don't get pulled into the application bundle and instead are expected to be defined on global by some other means. You could similarly designate nedb as an external in your webpack config and pull the Node version into your application via script tag or defining a reference to it on global some other way.



        Another solution would be to create a webpack resolver plugin to override how the problematic requires for "./lib/customUtils.js" and "./lib/storage.js" get resolved, bypassing the resolution step that inspects package.browser for aliases for those file paths.



        See the webpack documentation for how to pass a custom resolver plugin in your Webpack config. See the wepback/enhanced-resolve documentation for additional details on how plugins are defined and how they work.



        Essentially, a plugin is an object with an apply method that takes a resolver instance and performs some step of the file resolution process. In the example below, we test to see whether the current file being resolved is in the nedb package and whether it's one of the two problematic browser aliases. If so, we exit the resolution process with the correct paths to the files. Otherwise we do nothing and defer to the normal resolution process.



        // Prevents nedb from substituting browser storage when running from the
        // Electron renderer thread.
        const fixNedbForElectronRenderer =
        apply(resolver)
        resolver
        // Plug in after the description file (package.json) has been
        // identified for the import, which makes sure we're not getting
        // mixed up with a different package.
        .getHook("beforeDescribed-relative")
        .tapAsync(
        "FixNedbForElectronRenderer",
        (request, resolveContext, callback) =>
        // When a require/import matches the target files, we
        // short-circuit the Webpack resolution process by calling the
        // callback with the finalized request object -- meaning that
        // the `path` is pointing at the file that should be imported.
        const isNedbImport = request.descriptionFileData["name"] === "nedb"

        if (isNedbImport && /storage(.js)?/.test(request.path))
        const newRequest = Object.assign(, request,
        path: resolver.join(
        request.descriptionFileRoot,
        "lib/storage.js"
        )
        )
        callback(null, newRequest)
        else if (
        isNedbImport &&
        /customUtils(.js)?/.test(request.path)
        )
        const newRequest = Object.assign(, request,
        path: resolver.join(
        request.descriptionFileRoot,
        "lib/customUtils.js"
        )
        )
        callback(null, newRequest)
        else
        // Calling `callback` with no parameters proceeds with the
        // normal resolution process.
        return callback()


        )



        // Register the resolver plugin in the webpack config
        const config =
        resolve:
        plugins: [fixNedbForElectronRenderer]







        share|improve this answer













        As you stated in your question and per this Github issue on the nedb package the root cause of your issue is that webpack's file resolution process reads the package.browser key in order to alias specific file paths to a different location when the target build is browser or some other value that will cause it to inspect the package.browser property.



        electron-vue appears to sidestep the webpack bundling issue by treating all NPM dependencies as externals so that they don't get pulled into the application bundle and instead are expected to be defined on global by some other means. You could similarly designate nedb as an external in your webpack config and pull the Node version into your application via script tag or defining a reference to it on global some other way.



        Another solution would be to create a webpack resolver plugin to override how the problematic requires for "./lib/customUtils.js" and "./lib/storage.js" get resolved, bypassing the resolution step that inspects package.browser for aliases for those file paths.



        See the webpack documentation for how to pass a custom resolver plugin in your Webpack config. See the wepback/enhanced-resolve documentation for additional details on how plugins are defined and how they work.



        Essentially, a plugin is an object with an apply method that takes a resolver instance and performs some step of the file resolution process. In the example below, we test to see whether the current file being resolved is in the nedb package and whether it's one of the two problematic browser aliases. If so, we exit the resolution process with the correct paths to the files. Otherwise we do nothing and defer to the normal resolution process.



        // Prevents nedb from substituting browser storage when running from the
        // Electron renderer thread.
        const fixNedbForElectronRenderer =
        apply(resolver)
        resolver
        // Plug in after the description file (package.json) has been
        // identified for the import, which makes sure we're not getting
        // mixed up with a different package.
        .getHook("beforeDescribed-relative")
        .tapAsync(
        "FixNedbForElectronRenderer",
        (request, resolveContext, callback) =>
        // When a require/import matches the target files, we
        // short-circuit the Webpack resolution process by calling the
        // callback with the finalized request object -- meaning that
        // the `path` is pointing at the file that should be imported.
        const isNedbImport = request.descriptionFileData["name"] === "nedb"

        if (isNedbImport && /storage(.js)?/.test(request.path))
        const newRequest = Object.assign(, request,
        path: resolver.join(
        request.descriptionFileRoot,
        "lib/storage.js"
        )
        )
        callback(null, newRequest)
        else if (
        isNedbImport &&
        /customUtils(.js)?/.test(request.path)
        )
        const newRequest = Object.assign(, request,
        path: resolver.join(
        request.descriptionFileRoot,
        "lib/customUtils.js"
        )
        )
        callback(null, newRequest)
        else
        // Calling `callback` with no parameters proceeds with the
        // normal resolution process.
        return callback()


        )



        // Register the resolver plugin in the webpack config
        const config =
        resolve:
        plugins: [fixNedbForElectronRenderer]








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Apr 7 at 19:03









        jeebayjeebay

        4712 silver badges4 bronze badges




        4712 silver badges4 bronze badges


























            4
















            You don't need to run the database on the renderer process, instead of that you could run other database that you would like, like sql, sqlite, mongodb, etc, on main process.



            If you don't mind switching database, here is how you could achieve this. In Electron exist a class callled ipcMain and ipcRenderer, this classes are used to make renderer process and main process comunicate. You can send/receive any type of data with ipc.



            Here is an example:



            Renderer.js



            const btnSave = document.getElementById('btn-save')

            // Get any data from forms, etc


            btn.addEventListener('click', () =>
            // ipcRender sends the data via 'receive-data-to-save-in-database' channel, you
            // you can send any type of data, and have has many args you want. In this case I
            // sent a a empty object
            ipcRenderer.send('receive-data-to-save-in-database', )
            )


            Main.js



            // ipcMain listens to channel 'receive-data-to-save-in-database'
            ipcMain.on('receive-data-to-save-in-database', (event, args) =>
            // Code to save in database
            // The empty object will be received in args parameter
            )


            It's not what you wanted, but is a workaround.



            For more information, I suggest you go:



            ipcRenderer Docs
            ipcMain Docs






            share|improve this answer




















            • 2





              Thanks for the thoughts! My understanding is that it's actually not so good to run things like databases on the main process (see medium.freecodecamp.org/… and github.com/louischatriot/nedb/issues/531#issuecomment-477769752). I'm also looking to keep things simple from a debugging standpoint by staying on one thread while I develop my prototype. Lastly, I prefer nedb because it is pure JS.

              – acjay
              Apr 2 at 11:22















            4
















            You don't need to run the database on the renderer process, instead of that you could run other database that you would like, like sql, sqlite, mongodb, etc, on main process.



            If you don't mind switching database, here is how you could achieve this. In Electron exist a class callled ipcMain and ipcRenderer, this classes are used to make renderer process and main process comunicate. You can send/receive any type of data with ipc.



            Here is an example:



            Renderer.js



            const btnSave = document.getElementById('btn-save')

            // Get any data from forms, etc


            btn.addEventListener('click', () =>
            // ipcRender sends the data via 'receive-data-to-save-in-database' channel, you
            // you can send any type of data, and have has many args you want. In this case I
            // sent a a empty object
            ipcRenderer.send('receive-data-to-save-in-database', )
            )


            Main.js



            // ipcMain listens to channel 'receive-data-to-save-in-database'
            ipcMain.on('receive-data-to-save-in-database', (event, args) =>
            // Code to save in database
            // The empty object will be received in args parameter
            )


            It's not what you wanted, but is a workaround.



            For more information, I suggest you go:



            ipcRenderer Docs
            ipcMain Docs






            share|improve this answer




















            • 2





              Thanks for the thoughts! My understanding is that it's actually not so good to run things like databases on the main process (see medium.freecodecamp.org/… and github.com/louischatriot/nedb/issues/531#issuecomment-477769752). I'm also looking to keep things simple from a debugging standpoint by staying on one thread while I develop my prototype. Lastly, I prefer nedb because it is pure JS.

              – acjay
              Apr 2 at 11:22













            4














            4










            4









            You don't need to run the database on the renderer process, instead of that you could run other database that you would like, like sql, sqlite, mongodb, etc, on main process.



            If you don't mind switching database, here is how you could achieve this. In Electron exist a class callled ipcMain and ipcRenderer, this classes are used to make renderer process and main process comunicate. You can send/receive any type of data with ipc.



            Here is an example:



            Renderer.js



            const btnSave = document.getElementById('btn-save')

            // Get any data from forms, etc


            btn.addEventListener('click', () =>
            // ipcRender sends the data via 'receive-data-to-save-in-database' channel, you
            // you can send any type of data, and have has many args you want. In this case I
            // sent a a empty object
            ipcRenderer.send('receive-data-to-save-in-database', )
            )


            Main.js



            // ipcMain listens to channel 'receive-data-to-save-in-database'
            ipcMain.on('receive-data-to-save-in-database', (event, args) =>
            // Code to save in database
            // The empty object will be received in args parameter
            )


            It's not what you wanted, but is a workaround.



            For more information, I suggest you go:



            ipcRenderer Docs
            ipcMain Docs






            share|improve this answer













            You don't need to run the database on the renderer process, instead of that you could run other database that you would like, like sql, sqlite, mongodb, etc, on main process.



            If you don't mind switching database, here is how you could achieve this. In Electron exist a class callled ipcMain and ipcRenderer, this classes are used to make renderer process and main process comunicate. You can send/receive any type of data with ipc.



            Here is an example:



            Renderer.js



            const btnSave = document.getElementById('btn-save')

            // Get any data from forms, etc


            btn.addEventListener('click', () =>
            // ipcRender sends the data via 'receive-data-to-save-in-database' channel, you
            // you can send any type of data, and have has many args you want. In this case I
            // sent a a empty object
            ipcRenderer.send('receive-data-to-save-in-database', )
            )


            Main.js



            // ipcMain listens to channel 'receive-data-to-save-in-database'
            ipcMain.on('receive-data-to-save-in-database', (event, args) =>
            // Code to save in database
            // The empty object will be received in args parameter
            )


            It's not what you wanted, but is a workaround.



            For more information, I suggest you go:



            ipcRenderer Docs
            ipcMain Docs







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 1 at 19:25









            leandrojesus-programmerleandrojesus-programmer

            1048 bronze badges




            1048 bronze badges










            • 2





              Thanks for the thoughts! My understanding is that it's actually not so good to run things like databases on the main process (see medium.freecodecamp.org/… and github.com/louischatriot/nedb/issues/531#issuecomment-477769752). I'm also looking to keep things simple from a debugging standpoint by staying on one thread while I develop my prototype. Lastly, I prefer nedb because it is pure JS.

              – acjay
              Apr 2 at 11:22












            • 2





              Thanks for the thoughts! My understanding is that it's actually not so good to run things like databases on the main process (see medium.freecodecamp.org/… and github.com/louischatriot/nedb/issues/531#issuecomment-477769752). I'm also looking to keep things simple from a debugging standpoint by staying on one thread while I develop my prototype. Lastly, I prefer nedb because it is pure JS.

              – acjay
              Apr 2 at 11:22







            2




            2





            Thanks for the thoughts! My understanding is that it's actually not so good to run things like databases on the main process (see medium.freecodecamp.org/… and github.com/louischatriot/nedb/issues/531#issuecomment-477769752). I'm also looking to keep things simple from a debugging standpoint by staying on one thread while I develop my prototype. Lastly, I prefer nedb because it is pure JS.

            – acjay
            Apr 2 at 11:22





            Thanks for the thoughts! My understanding is that it's actually not so good to run things like databases on the main process (see medium.freecodecamp.org/… and github.com/louischatriot/nedb/issues/531#issuecomment-477769752). I'm also looking to keep things simple from a debugging standpoint by staying on one thread while I develop my prototype. Lastly, I prefer nedb because it is pure JS.

            – acjay
            Apr 2 at 11:22

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55389659%2fpersist-nedb-to-disk-in-electron-renderer-process-webpack-electron-nedb-configu%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript