Giter Club home page Giter Club logo

node-hook's Introduction

node-hook

Run source transform function on Node require

NPM

Build status dependencies devdependencies semantic-release

Install and use

npm install --save node-hook

Before loading desired .js files, install hook

var hook = require('node-hook');

function logLoadedFilename(source, filename) {
    return 'console.log("' + filename + '");\n' + source;
}
hook.hook('.js', logLoadedFilename);
require('./dummy');
// prints fulle dummy.js filename, runs dummy.js

hook.unhook('.js'); // removes your own transform

remember: Nodejs caches compiled modules, so if the transform is not working, you might need to delete the cached entry in require.cache, then call require(filename) again to force reload.

Related: Node require replacement really-need.

You can hook several transformers thanks to the code submitted by djulien

Existing transform

You can get the current transform and run any source through it. For example to see how the current source looks when loaded but before evaluated

const filename = resolve('./call-foo.js')
const transform = Module._extensions['.js']
const fakeModule = {
  _compile: source => {
    console.log('transformed code')
    console.log(source)
  }
}
transform(fakeModule, filename)

Small print

Author: Gleb Bahmutov © 2013

License: MIT - do anything with the code, but don't blame me if it does not work.

Support: if you find any problems with this module, email / tweet / open issue on Github

node-hook's People

Contributors

bahmutov avatar djulien avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

node-hook's Issues

Warn if no code is returned

it should warn if the hook function does not return anything (can cause weird bugs)

const hook = require('node-hook')
function instrument(source, filename) {
  console.log('instrumenting %s for data-cover', filename)
  // returns undefined
}
hook.hook('.js', instrument)
process.on('exit', function () {
  console.log('data-cover is done')
  hook.unhook('.js')
})

relative paths break?

I'm using the following test code, and am getting an interesting error.

var hook = require('node-hook');
function preprocess(source, filename) {
  return source;
}
['js','jsx'].forEach(function(ext) { hook.hook('.' + ext, preprocess); });

Pretty straight-forward pass-through processing, the expectation is that this, of course, does nothing. Instead, it causes and error on the following line later in the same file (line 19 in the file) :

...
var RouteSet = require('../lib/site/routes');
...

Claiming:

module.js:328
    throw err;
    ^

Error: Cannot find module '../lib/site/routes'
    at Function.Module._resolveFilename (module.js:326:15)
    at Function.Module._load (module.js:277:25)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (J:\Junctions\Users\Mike\Documents\Git projects\projects\BezierInfo-2\pages\test.js:19:16)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:430:10)

Without node-hook, this works just fine, it's just a relative file location, but with node-hook, things no longer work for relative requirements... I tried to change it to ../lib/sites/routes.js because maybe the automatic extension from node's site isn't kicking in, but that just gives the same error:

module.js:328
    throw err;
    ^

Error: Cannot find module '../lib/site/routes.js'
    at Function.Module._resolveFilename (module.js:326:15)
    at Function.Module._load (module.js:277:25)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (J:\Junctions\Users\Mike\Documents\Git projects\projects\BezierInfo-2\pages\test.js:19:16)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:430:10)

Cannot read property '.js' of undefined

Hi,

I am trying to hook a function in node module, but I got error as mentioned in the title, below is my code:

var hook = require('node-hook');
function Request(method, url) {
alert(url);
}
hook.hook('.js', Request);
require('./node_modules/module_name/index');

Is it possible on the way I am trying to archive?

require of JSON returns empty object

On the line 73 is called _compile() and it results into empty object when the content of required module is JSON. I changed my code and assign result of JSON.parse() directly to exports, if extension is '.json'. I'm not sure if it is correct fix and maybe it brings other issues.

not working when server code is precompiled

I've been using this plugin on the server to help render universal apps. The app requires in some code that imports scss, which on the server, is duly ignored. This works find when i was running the server and the first step was to call babel-core/register.

Now that I am trying to remove babel from my prod code i find that the hook is no longer working. By removing babel from my prod code I mean instead i use babel-cli to precompile the server. I then get node to run the compiled code.

I noticed you mentioned clearing cache in your readme; but i don't believe the cache is the problem as the error message suggests the hook isn't doing anything :

Error: Cannot find module './mainLayout.scss'

It seems to me babel register and babel-cli compile in different ways, which doesn't sound right?

have you any idea?

To help, here is a quick place to see that code changes I've made to my app :
https://github.com/peter-mouland/react-lego/compare/remove-prod-babel

the whole app (with this new branch) is available here:
https://github.com/peter-mouland/react-lego/tree/remove-prod-babel

Check if there is registered extension before unhooking

If we try to unhook our hook without registering, causes a crash

const hook = require('node-hook')
process.on('exit', function () {
  console.log('data-cover is done')
  hook.unhook('.js')
})
node_modules/node-hook/index.js:88
  nestedTransforms[extension].pop(); //assumes no stack underflow
                             ^
TypeError: Cannot read property 'pop' of undefined
    at Object.unhook (node_modules/node-hook/index.js:88:30)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.