1'use strict'; 2 3// If user passed `-c` or `--check` arguments to Node, check its syntax 4// instead of actually running the file. 5 6const { URL } = require('internal/url'); 7const { getOptionValue } = require('internal/options'); 8const { 9 prepareMainThreadExecution, 10 markBootstrapComplete, 11} = require('internal/process/pre_execution'); 12 13const { 14 readStdin, 15} = require('internal/process/execution'); 16 17const { pathToFileURL } = require('url'); 18 19const { 20 Module: { 21 _resolveFilename: resolveCJSModuleName, 22 }, 23 wrapSafe, 24} = require('internal/modules/cjs/loader'); 25 26// TODO(joyeecheung): not every one of these are necessary 27prepareMainThreadExecution(true); 28 29if (process.argv[1] && process.argv[1] !== '-') { 30 // Expand process.argv[1] into a full path. 31 const path = require('path'); 32 process.argv[1] = path.resolve(process.argv[1]); 33 34 // Read the source. 35 const filename = resolveCJSModuleName(process.argv[1]); 36 37 const fs = require('fs'); 38 const source = fs.readFileSync(filename, 'utf-8'); 39 40 markBootstrapComplete(); 41 42 loadESMIfNeeded(() => checkSyntax(source, filename)); 43} else { 44 markBootstrapComplete(); 45 46 loadESMIfNeeded(() => readStdin((code) => { 47 checkSyntax(code, '[stdin]'); 48 })); 49} 50 51function loadESMIfNeeded(cb) { 52 const { getOptionValue } = require('internal/options'); 53 const hasModulePreImport = getOptionValue('--import').length > 0; 54 55 if (hasModulePreImport) { 56 const { loadESM } = require('internal/process/esm_loader'); 57 loadESM(cb); 58 return; 59 } 60 cb(); 61} 62 63async function checkSyntax(source, filename) { 64 let isModule = true; 65 if (filename === '[stdin]' || filename === '[eval]') { 66 isModule = getOptionValue('--input-type') === 'module' || 67 (getOptionValue('--experimental-default-type') === 'module' && getOptionValue('--input-type') !== 'commonjs'); 68 } else { 69 const { defaultResolve } = require('internal/modules/esm/resolve'); 70 const { defaultGetFormat } = require('internal/modules/esm/get_format'); 71 const { url } = await defaultResolve(pathToFileURL(filename).toString()); 72 const format = await defaultGetFormat(new URL(url)); 73 isModule = format === 'module'; 74 } 75 76 if (isModule) { 77 const { ModuleWrap } = internalBinding('module_wrap'); 78 new ModuleWrap(filename, undefined, source, 0, 0); 79 return; 80 } 81 82 const { loadESM } = require('internal/process/esm_loader'); 83 const { handleMainPromise } = require('internal/modules/run_main'); 84 handleMainPromise(loadESM((loader) => wrapSafe(filename, source))); 85} 86