meta pixel

Trying to do without require in Node.js


    Posted by Evgeniy Arshanskiy

    on Apr 29th 2025


There is some conceptual difference in how external libraries and project files are included. And the standard mechanism for this is the same. The second point that confuses me is the somewhat confused logic of the require itself.

As a result, I wanted to at least connect my files in a self-made, but more transparent way. In parallel, adding a few additional features. This is how the functions described below appeared.

get_modules =( string, modules ={} )-> groups =string .split ' ' for group in groups items =group .split ':' id =items[ 0 ] named =items .length > 1 name =if named then items[ 1 ] else id .replace( /\-/g, '_' ) obj =require id obj =obj[ name ] if named and obj[ name ] modules[ name ] =obj modules Auxiliary function for connecting standard modules. Works as follows. After, for example, modules =get_modules 'fs path coffeescript vm' in the modules object, we will get the standard modules fs, path and others, which can be accessed accordingly modules .[module name] .[function name].

So read =( file )-> path =modules .path .join __dirname, file modules .fs .readFileSync path, 'utf8' - returns the contents of the source file. compile =( coffee, file )-> options = inlineMap: false, sourceMap: true, bare: true, filename: file res =modules .coffeescript .compile coffee, options res .js - Translates CoffeeScript to JavaScript. ``` evaluate =( js, filename ='', lineOffset =0, columnOffset =0 )-> modules .vm .runInThisContext js, { filename, lineOffset, columnOffset }

- executes JavaScript code. And all together, in case we want to wrap our code in some kind of wrapper function: get_wrapper =( id, args )-> file =id + '.coffee' #путь к файлу str =@read( file ) .replace( /\n/g, "\n\t" ) #добавляем отступы coffee ="( #{ args } )->\n\t#{ str }" #собственно "оборачиваем" в функцию js =@compile coffee, file @evaluate js, file#, 1, 0 `` whereargs` is a string with comma-separated variable names that will become available as "global" in this module.

source code

Evgeniy ArshanskiyTechnology Expert