从 Node.js 应用程序请求 CoffeeScript 会出现找不到模块错误

Requiring CoffeeScript from Node.js application gives cannot find module error

我试图从 Node.js 应用程序中获取 CoffeeScript 文件,但 Node.js 给出了错误 Error: Cannot find module 'something'。这样做的正确方法是什么?如果我事先编译 CoffeeScript 代码,它可以工作,但我不想这样做。

test.js:

require('coffee-script').register();

require('something');

something.coffee:

console.log('Hello World!');

控制台输出:

> node test.js

module.js:340
    throw err;
          ^
Error: Cannot find module 'something'
  at Function.Module._resolveFilename (module.js:338:15)
  at Function.Module._load (module.js:280:25)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at Object.<anonymous> (C:\Users\Sami\Desktop\smallscale\test.js:3:1)
  at Module._compile (module.js:456:26)
  at Object.Module._extensions..js (module.js:474:10)
  at Module.load (module.js:356:32)
  at Function.Module._load (module.js:312:12)
  at Function.Module.runMain (module.js:497:10)
  at startup (node.js:119:16)
  at node.js:906:3

您似乎正在尝试 require() 使用该结构的文件 require() 模块。

如果你 require() 没有给 require() 文件路径(绝对或相对),Node.js 将在 /node_modules 目录。您可以阅读文档 here.

尝试将您的模块作为 JavaScript 文件,如下所示:

require('./something')

(并确保 './something' 是从您需要模块的位置到模块在您的应用程序结构中所在位置的路径,或者使用绝对路径)。