node.js: Error: Cannot find module

node.js: Error: Cannot find module

为什么会出现此错误?

Node v8.9.1

代码

var childProcess = require('child_process'),
    phantomjs = require('/var/bin/node_modules/phantomjs-prebuilt');

console.error = function(){
    require('system').stderr.write(Array.prototype.join.call(arguments, ' ')+'\n');
    phantomjs.exit(1);
};

console.log('hey', phantomjs.path)
console.error('error')

childProcess.execFile(phantomjs.path, require('system').args, function(err, stdout, stderr){
    if(err){
        console.error(err);
    }

    if(stderr){
        console.error(stderr);
    }

    console.log(stdout);
});

错误

# /var/bin/node_modules/phantomjs-prebuilt/bin/phantomjs phantom.js
Error: Cannot find module 'path'

  phantomjs://platform/bootstrap.js:299 in require
  phantomjs://platform/bootstrap.js:263 in require
  phantomjs://platform/phantomjs.js:10
hey undefined
TypeError: undefined is not a function (evaluating 'phantomjs.exit(1)')

  phantomjs://code/phantom.js:6 in error
error

system不是Node内置模块,it's part of PhantomJS. It won't be available if you're just running your script with the standard node command. As shown in the documentation,需要使用phantomjs命令,像这样:

phantomjs phantom.js