summaryrefslogtreecommitdiff
path: root/lib/internal/main/check_syntax.js
blob: 392fadb99ff668affa37a79527301f4350bef022 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict';

// If user passed `-c` or `--check` arguments to Node, check its syntax
// instead of actually running the file.

const {
  prepareMainThreadExecution
} = require('internal/bootstrap/pre_execution');

const {
  readStdin
} = require('internal/process/execution');

const CJSModule = require('internal/modules/cjs/loader');
const vm = require('vm');
const {
  stripShebang, stripBOM
} = require('internal/modules/cjs/helpers');


if (process.argv[1] && process.argv[1] !== '-') {
  // Expand process.argv[1] into a full path.
  const path = require('path');
  process.argv[1] = path.resolve(process.argv[1]);
  // Read the source.
  const filename = CJSModule._resolveFilename(process.argv[1]);

  const fs = require('fs');
  const source = fs.readFileSync(filename, 'utf-8');

  // TODO(joyeecheung): not every one of these are necessary
  prepareMainThreadExecution();
  markBootstrapComplete();

  checkScriptSyntax(source, filename);
} else {
  // TODO(joyeecheung): not every one of these are necessary
  prepareMainThreadExecution();
  markBootstrapComplete();

  readStdin((code) => {
    checkScriptSyntax(code, '[stdin]');
  });
}

function checkScriptSyntax(source, filename) {
  // Remove Shebang.
  source = stripShebang(source);
  // Remove BOM.
  source = stripBOM(source);
  // Wrap it.
  source = CJSModule.wrap(source);
  // Compile the script, this will throw if it fails.
  new vm.Script(source, { displayErrors: true, filename });
}