Skip to content

Instantly share code, notes, and snippets.

@bmwalters
Created January 8, 2017 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmwalters/a0dd2658fac472aafa9efd08f787c1a9 to your computer and use it in GitHub Desktop.
Save bmwalters/a0dd2658fac472aafa9efd08f787c1a9 to your computer and use it in GitHub Desktop.
Load Lua modules from the node_modules folder!
local string = require("string")
local pathlib = require("pl.path")
local filelib = require("pl.file")
local function split(str, sep)
local ret = {}
local last_sep = 1
for i = 1, #str do
if string.byte(str, i, i) == string.byte(sep) then
ret[#ret + 1] = string.sub(str, last_sep, i - 1)
last_sep = i + 1
end
end
ret[#ret + 1] = string.sub(str, last_sep)
return ret
end
local function load_lua_module(path)
return loadfile(path)
end
local function load_as_file(path)
if pathlib.isfile(path) then
return load_lua_module(path)
end
if pathlib.isfile(path .. ".lua") then
return load_lua_module(path .. ".lua")
end
-- todo: binary modules
end
local function load_as_directory(path)
if pathlib.isfile(path .. "/package.json") then
local info = filelib.read(path .. "/package.json")
local main = string.match(info, "\"main\":%s*\"(.-)\"")
if main then
return load_as_file(path .. "/" .. main)
end
end
if pathlib.isfile(path .. "/init.lua") then
return load_lua_module(path .. "/init.lua")
end
-- todo: binary modules
end
local function node_modules_paths(start)
local parts = split(start, "/")
local dirs = {}
for i = #parts, 1, -1 do
if parts[i] ~= "node_modules" then
local dir = ""
for i2 = 1, i do
dir = dir .. parts[i2] .. "/"
end
dirs[#dirs + 1] = dir .. "node_modules"
end
end
return dirs
end
local function load_node_modules(name, start)
local dirs = node_modules_paths(start)
for i = 1, #dirs do
local path = dirs[i] .. "/" .. name
local filemod = load_as_file(path)
if filemod then return filemod end
local dirmod = load_as_directory(path)
if dirmod then return dirmod end
end
end
local searchers = package.searchers or package.loaders
searchers[#searchers + 1] = function(name)
return load_node_modules(name, pathlib.currentdir())
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment