Tech notes for nodejs

Javascript: Selenium setup in NodeJS with Firefox and ES6 modules

First install npm install selenium-webdriver. I'm on 4.0.0.

Then import Selenium with ES6 modules. We'll rename them since they're not built with ES6 modules in mind.

import * as webdriver from 'selenium-webdriver'
import * as firefox from 'selenium-webdriver/firefox'
let ff = firefox.default; 
let wd = webdriver.default

Then tell Selenium where your Firefox binary is and create the selenium instance.

let options = new ff.Options().setBinary('/usr/bin/firefox')
let browser = new wd.Builder().forBrowser('firefox').setFirefoxOptions(options).build()

Selenium will respond with promises. This is a little annoying so let's use an async function and use await.

async function test() {
  await browser.get("http://localhost:8080/")
  let next = await browser.findElement(wd.By.linkText("next"))
  let pageSource = await browser.getPageSource()
  let hasPage = pageSource.indexOf("Page 2 of 2") != -1
  assert.equal(hasPage, true, "Checking if we're on page 2")

Finally we use the findElement method, once we've loaded a page, and then use the By class to find the link text. Then we click on it.

We then get the page source and do some string searching on that to use a normal nodejs assert statement.

javascript selenium nodejs

NodeJS: Write javascript to JSON file

If you want to write your javascript object to a json file, it's easy enough:

fs.writeFileSync('thefilename.json', JSON.stringify(your_object))

This will synchronously write your file, too, unlike the other variant which calls a callback when it's finished.

nodejs javascript

NodeJS: Increase allocated memory

You may find NodeJS crashes due to lack of memory. You can increase it as follows (to 6gb):

node --max-old-space-size=6144

nodejs javascript

Simple SQLite3 and NodeJS interactions

Firstly install sqlite3, npm -g install sqlite3 then:

const sqlite3 = require('sqlite3');
var yourdb = new sqlite3.Database('yourdb.sqlite3');
yourdb.all("select * from yourtable", [], (e, row) => {
nodejs sql-sqlite javascript

Page 2 of 2
Click me