A custom Node.js utility library for common string operations such as capitalize
, camelCase
, slugify
, and simple greetings.
To start building the package, initialize package.json
:
npm init
Or use the quick setup with default values:
npm init -y
π οΈ What Does This Project Do?
This project demonstrates how to build a custom Node.js package that includes a utility library for string operations:
Capitalize the first letter of a string
Convert strings to camelCase
Generate URL-friendly slugs
Display greeting messages
π Project Structure
custom-package/
βββ index.js
βββ package.json
βββ README.md
βββ utils/
βββ capitalize.js
βββ camelCase.js
βββ slugify.js
βββ greeting.js
βοΈ Write Utility Functions
utils/capitalize.js
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
module.exports = capitalize;
utils/camelCase.js
function camelCase(str) {
return str
.replace(/\s(.)/g, (match, group1) => group1.toUpperCase())
.replace(/\s/g, '')
.replace(/^(.)/, (match, group1) => group1.toLowerCase());
}
module.exports = camelCase;
utils/slugify.js
function slugify(str) {
return str
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.trim()
.replace(/[\s_-]+/g, '-');
}
module.exports = slugify;
utils/greeting.js
function sayHello(name) {
return `Hello, ${name}!`;
}
module.exports = sayHello;
π§© Create index.js (Package Entry Point)
const capitalize = require('./utils/capitalize');
const camelCase = require('./utils/camelCase');
const slugify = require('./utils/slugify');
const sayHello = require('./utils/greeting');
module.exports = {
capitalize,
camelCase,
slugify,
sayHello
};
π Test the Package Locally
Step 1: Link the Package Globally
In your package root directory:
npm link
Step 2: Create a New Project Folder
mkdir test-custom-package
cd test-custom-package
npm init -y
Step 3: Link Your Custom Package
npm link custom-package
Step 4: Create a Test File
// index.js
const utils = require('custom-package');
console.log(utils.sayHello('Rana')); // Hello, Rana!
console.log(utils.capitalize('world')); // World
console.log(utils.camelCase('hello world app')); // helloWorldApp
console.log(utils.slugify('Node.js String Utils')); // node-js-string-utils
Step 5: Run the Test File
node index.js
You should see your functions working as expected!
π€ Optional: Publish to npm
Rename your package with a unique name or scoped name (e.g., "@yourname/custom-package")
Login to npm:
npm login
Publish:
npm publish --access public