Skip to content

Instantly share code, notes, and snippets.

@bermanboris
Last active July 2, 2020 03:50
Show Gist options
  • Save bermanboris/1c24cb9fd77181c03989fe3b1be2a726 to your computer and use it in GitHub Desktop.
Save bermanboris/1c24cb9fd77181c03989fe3b1be2a726 to your computer and use it in GitHub Desktop.
PhantomJS usage in TypeScript ( Node.js )
// Usage:
//
// npm install phantom @types/phantom --save
// tsc --target "es6" ./phantomjs-example.ts
// node phantomjs-example.js
//
import * as phantom from "phantom";
async function getPageContent(url: string) {
const instance: phantom.PhantomJS = await phantom.create();
const page: phantom.WebPage = await instance.createPage();
const status: string = await page.open(url);
const content = await page.property('content');
console.log(content);
await instance.exit();
}
getPageContent("http://github.com");
@paulgmathew
Copy link

Hi! im not able to run the js with node .It is giving me this error
/Users/p0m00hm/Documents/typeScriptTest/phantomjs-example.js:9
import * as phantom from "phantom";
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)

@bermanboris
Copy link
Author

bermanboris commented May 22, 2017

You have to transpile TS to JS first. You can do that with "tsc".

  1. Transpile TypeScript file to JavaScript

tsc phantomjs-example.ts

  1. Run JavaScript

node phantomjs-example.js

@chusri
Copy link

chusri commented Jul 2, 2020

Thanks for your snippets.

btw, you can add the ts-node to run the .ts file directly.

ts-node phantomjs-example.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment