Enhance Your File Operations with Filenamify A Comprehensive API Guide

Introduction to Filenamify

Filenamify is a powerful library designed to make working with file and directory names seamless. From sanitizing filenames to ensuring compatibility across different file systems, here’s a comprehensive guide to its dozens of useful APIs with examples to boost your productivity.

Core API Functions

1. filenamify()

Ensures a file name is safe to use, replacing invalid characters.

  
    const filenamify = require('filenamify');
    console.log(filenamify('foo:bar')); // Outputs: foo!bar
  

2. filenamifyPath()

Sanitizes all parts of a path.

  
    const filenamifyPath = require('filenamify').path;
    console.log(filenamifyPath('/foo/bar:baz')); // Outputs: /foo/bar!baz
  

3. filenamifyCustom()

Use a custom replacement for invalid characters.

  
    const filenamify = require('filenamify');
    console.log(filenamify('foo:bar', {replacement: '_'})); // Outputs: foo_bar
  

4. filenamifyPathCustom()

Sanitize all parts of a path with custom replacement.

  
    const filenamifyPath = require('filenamify').path;
    console.log(filenamifyPath('/foo/bar:baz', {replacement: '_'})); // Outputs: /foo/bar_baz
  

5. filenamifyWithOptions()

Set options such as maxLength for filenames.

  
    const filenamify = require('filenamify');
    console.log(filenamify('foo:bar:baz', {maxLength: 8})); // Outputs: foo!bar!
  

Application Example

Now let’s see a simple app that demonstrates these APIs in action:

  
    const express = require('express');
    const filenamify = require('filenamify');
    const app = express();

    app.get('/sanitize/:filename', (req, res) => {
      const sanitizedFilename = filenamify(req.params.filename);
      res.send(`Sanitized filename: ${sanitizedFilename}`);
    });

    app.get('/sanitizePath/:filepath', (req, res) => {
      const sanitizedFilePath = filenamify.path(req.params.filepath);
      res.send(`Sanitized file path: ${sanitizedFilePath}`);
    });

    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
  

With the above sample application, you can effortlessly sanitize filenames and paths.

For more detailed documentation, check out the official Filenamify repository.

Hash: 6293d34fc746578dc9d425c255cb02858d4338caa5c50d4cba4a63c8c5e7c0c9

Leave a Reply

Your email address will not be published. Required fields are marked *