Extending Array.prototype in Node.js, from a require'd file

情到浓时终转凉″ 提交于 2019-12-04 08:26:08

Every command in the REPL is executed via vm.runInContext with a shared context object. This object is created at REPL initialization by copying everything from the global object. Since the require'd module will only extend Array.prototype after it has been copied to the context object, the modified version is never exposed.

Or at least that's what I could deduce from the source code. I know nothing about the inner workings of V8 :) And as you probably have found out by now, your example works fine outside the REPL.

You can create a file which includes your extensions:

array.extensions.js

if(!Array.prototype.Last){
    Array.prototype.Last = function(){
        return this.slice(-1)[0];
    }
}

if(!Array.prototype.First){
    Array.prototype.First = function(){
        return this[0];
    }
}

then include this file to your startup file.

app.js:

require('{path}/array.extensions');
var express = require('express');
/* rest of your code */

referring this file once on startup is enough to use...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!