filename-to-module-name

Get the shortest name file can be required by in Node.js

Usage no npm install needed!

<script type="module">
  import filenameToModuleName from 'https://cdn.skypack.dev/filename-to-module-name';
</script>

README

npm

filename-to-module-name

Build Status Dependency Status

Returns the shortest module name for the given filename.

Here is a pseudocode, effectively the inverse of require.resolve algorithm used by Node:

1. If X is a directory,
   a. return basename(X)
   b. STOP
2. Let Y be X with ".js", ".json" or ".node" removed
3. If exists(Y), return basename(X). STOP
4. For E in [".js", ".json", ".node"],
   a. If X ends with E, return basename(Y). STOP
   b. If exists(Y + E), return basename(X). STOP
5. Return basename(X)

Example

var moduleName = require('filename-to-module-name');

moduleName('./index.js');
//=> "index"

API

filenameToModuleName(filename)

Returns the module name. filename should be a name of an existing file or directory.

Install

npm install filename-to-module-name

License

MIT