从可执行文件中打开 npm 模块中的文件 [英] Open file from npm module from executable

查看:42
本文介绍了从可执行文件中打开 npm 模块中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 npm 模块(@jcubic/lips)具有可执行文件和我想打开位于该模块目录中的文件.该模块是全局安装的.

I have npm module (@jcubic/lips) that have executable and I want to open file that is located in that module directory. The module is installed globally.

我想访问相对于模块中 bin 目录的文件 ../examples/helpers.lips 但可执行文件安装在/usr/bin/lips 中,我不知道如何访问模块.

I want to access file ../examples/helpers.lips relative to bin directory in my module but executable is installed in /usr/bin/lips and I don't know how to access the module.

如何访问该文件或获取模块的根目录?有跨平台解决方案吗?

How can I access that file, or get root directory of the module? Is there cross platform solution?

我的可执行文件是 lisp 解释器,我正在执行此代码:

My executable is lisp interpreter and I'm executing this code:

#!/usr/bin/env lips

(load "../examples/helpers.lips")

这是可以理解的,因为 CWD 是我从中调用脚本的目录.加载只是 fs.readFile + eval.

which is understandable because CWD is directory from which I invoked the script. Load is just fs.readFile + eval.

我的解释器是用 JavaScript 编写的,因此需要与 Node 中相同的工作方式,并且在 node 中访问的每个函数都可以在嘴唇中访问.但我想先加载那个文件,有重要的功能和宏.将来它可能会默认加载,但首先我需要访问该模块.如果它在从本地安装的 node_module 调用或作为来自 git repo 的源调用时也能工作,那就太好了.

My interpreter is written in JavaScript so require work the same as in Node and every function accessed in node can be accessed in lips. But I want to load that file first have have important functions and macros. In the future it maye be loaded by default but first I need to access the module. It would be nice if it also work when called from node_module installed locally or as source from git repo.

最近我了解到,如果添加处理程序,您可以将 require 与文本文件一起使用,这是访问模块内静态文件的唯一方法(使用 require("@jcubic/lips/examples/helpers.lips") 或更好的方法).如果我找到有关此的文章并更新问题,将尝试使用该未记录的功能.

Recently I've learnt that you can use require with text files if you add handler is this the only way to get access to static files inside a module (use require("@jcubic/lips/examples/helpers.lips") or is better way). Will try to use that undocumented feature if I find the article about this, and update the question.

推荐答案

在 Node.js 文档中找到解决方案 modules 是函数 require.resolve.

Found solution in Node.js docs for modules which is function require.resolve.

功能描述说:

使用内部的 require() 机制查找模块的位置,而不是加载模块,只需返回解析的文件名.

Use the internal require() machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.

所以这正是我所需要的,这是我使用的函数,在评估用户代码之前运行它:

so it was exactly what I've needed, This is my function I was using, run this before I evaluate user code:

function boostrap() {
    var path;
    try {
        path = require.resolve('./examples/helpers.lips');
    } catch (e) {
        path = require.resolve('@jcubic/lips/examples/helpers.lips');
    }
    var data = fs.readFileSync(path);
    return run(data, env);
}

这篇关于从可执行文件中打开 npm 模块中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆