Horje
qs - NPM

qs is a popular npm package used for serializing JavaScript objects into query strings. It provides an easy way to handle query parameters in web applications by converting object data into a format that can be appended to URLs for HTTP requests.

Prerequisites:

Features of npm qs

  • Query String Serialization: It efficiently converts objects into query strings, handling nested objects, arrays, and various data types.
  • Array Indexing: Supports array indices in query string serialization, ensuring accurate representation of array data.
  • Customization: Offers options to customize serialization behaviour, such as array formatting and encoding.
  • Parsing: Provides parsing uses to deserialize query strings back into JavaScript objects.

Steps to Create Application and Installing Package

Step 1: Create a new folder for your project in your terminal or command prompt.

mkdir qs-demo

Step 2: Navigate to the newly created folder.

cd qs-demo

Step 3: Initialize npm to create a package.json file.

npm init -y

Step 4: Install the qs package using npm.

npm install qs

Step 5: Create the index.js file.

Project Structure:

PS

Folder Structure

Dependencies

"dependencies": {
"qs": "^6.12.1"
}

Example 1: In this example, the qs package is used to serialize the data object into a query string using qs.stringify, which is then logged to the console. The serialized query string is then parsed back into an object using qs.parse.

JavaScript
//index.js

const qs = require('qs');
const data = {
    title: 'GeeksforGeeks',
    category: 'Programming',
    tags: ['JavaScript', 'Node.js', 'npm'],
};
const queryString = qs.stringify(data);
console.log('Serialized Query String:', queryString);
const res = qs.parse(queryString);
console.log('Parsed Data:', res);

Output:

E1

qs.stringify

Example 2: In this example, the qs package is used to serialize the data object, including nested objects and arrays, into a query string with dot notation enabled (allowDots: true). The serialized query string is then parsed back into an object using qs.parse.

JavaScript
//index.js

const qs = require('qs');
const data = {
    title: 'GeeksforGeeks',
    details: {
        category: 'Programming',
        tags: ['JavaScript', 'Node.js', 'npm'],
    },
    author: {
        name: 'Sandeep Jain',
        age: 30,
    },
};
const queryString = qs.stringify(data, {
    allowDots: true
});
console.log('Serialized Query String:', queryString);
const res = qs.parse(queryString);
console.log('Parsed Data:', res);

Output:

E2

serialize data object




Reffered: https://www.geeksforgeeks.org


Node.js

Related
multer - NPM multer - NPM
NPM Serve NPM Serve
NPM Bootstrap NPM Bootstrap
How to Use Node.js for Backend Web Development in 2024? How to Use Node.js for Backend Web Development in 2024?
NPM Version NPM Version

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15