How to use global URLSearchParams in node

后端 未结 4 1994
长发绾君心
长发绾君心 2020-12-18 18:23

I am writing a (client-side) JavaScript library (a node/angular module). In this library, I make use of the URLSearchParams class.

const form = new URLSearch         


        
相关标签:
4条回答
  • 2020-12-18 18:35

    If we want to support big range of nodejs versions in our application , we could use some dirty code like this :

    if(typeof URLSearchParams === 'undefined'){
        URLSearchParams = require('url').URLSearchParams;
    }
    

    Note: It is not best practice to require with a condition.

    0 讨论(0)
  • 2020-12-18 18:41

    Update: Node v10 has built-in availability of URLSearchParams on the global object so it can be used directly as anticipated in the question.

    Older versions of Node:

    One option is to set it as a global in the start-up script of the test runner:

    import { URLSearchParams } from 'url';
    global.URLSearchParams = URLSearchParams
    

    With Jest, for example, you would use the setupTestFrameworkScriptFile to point to the above start-up script.

    As a side note, if you wanted to achieve a similar outcome when creating a server-side Webpack bundle of universal code you can achieve this with the Webpack ProvidePlugin:

    {
      name: 'server',
      target: 'node',
      // ...
      plugins: [
        // ...
        new webpack.ProvidePlugin({
          URLSearchParams: ['url', 'URLSearchParams'],
          fetch: 'node-fetch',
        }),
      ],
    }
    
    0 讨论(0)
  • 2020-12-18 18:47

    You may use polifill @ungap/url-search-params https://www.npmjs.com/package/@ungap/url-search-params and for webpack may use @ungap/url-search-params/cjs

    Old NodeJS 8 (which isused in AWS and GCloud) does not support URLSearchParams so this polifill helps.

    In Node 10 when using TypeScript you may enable library dom which includes URLSearchParams implementation. Change tsconfig.json:

    {
      "compilerOptions": {
        "lib": [
          ...
          "dom"
          ...
        ]
      }
    }
    
    0 讨论(0)
  • 2020-12-18 18:49

    In AWS Lambda which uses Node8.10, I had to do:

    const {URLSearchParams} = require('url')
    const sp = new URLSearchParams(request.querystring)
    

    or

    const url = require('url')
    const sp = new url.URLSearchParams(request.querystring)
    
    0 讨论(0)
提交回复
热议问题