vm_compile.js (1456B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var vm = require( 'vm' ); 24 var wrap = require( './wrap.js' ); 25 26 27 // MAIN // 28 29 /** 30 * Compiles JavaScript source code for execution within a V8 virtual machine context. 31 * 32 * @private 33 * @param {string} filename - filename to associate with compiled source code 34 * @param {string} code - source code to compile 35 * @returns {Function} compiled source code wrapped within a function 36 */ 37 function compile( filename, code ) { 38 var script; 39 var opts; 40 41 // Wrap the source code similar to `require`: 42 code = wrap( code ); 43 44 // Compile the source code: 45 opts = { 46 'filename': filename, 47 'lineOffset': 0 48 }; 49 script = new vm.Script( code, opts ); 50 51 // Run the compiled code in the current V8 context: 52 opts = { 53 'displayErrors': true 54 }; 55 return script.runInThisContext( opts ); 56 } 57 58 59 // EXPORTS // 60 61 module.exports = compile;