# Nodejs - to a web app

**URL:** <https://community.haxe.org/t/nodejs-to-a-web-app/2967>\
**Category:** Haxe\
**Tags:** haxe-js, nodejs\
**Created:** [April 4, 2021, 8:12pm UTC](https://community.haxe.org/t/nodejs-to-a-web-app/2967 "2021-04-04T20:12:55Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![haxiomic](https://community.haxe.org/user_avatar/community.haxe.org/haxiomic/32/75_2.png) [@haxiomic](https://community.haxe.org/u/haxiomic)\
**Post date:** [April 4, 2021, 9:47pm UTC](https://community.haxe.org/t/nodejs-to-a-web-app/2967/4 "2021-04-04T21:47:48Z")

</div>

Gotcha, ok – does it use any node.js libraries like express? (Could you paste your package.json here?)

I’ll try to make a little tutorial for this

## Getting Setup

- First download and install the latest haxe (if you haven’t already)
- Install [Visual Studio Code](https://code.visualstudio.com/) and then install the [haxe plugin](https://marketplace.visualstudio.com/items?itemName=nadako.vshaxe)
- Next, make a new directory to hold the project and create the following:
  - `build.hxml` (empty – this will hold our haxe build options)
  - `src/Main.hx` (empty – this will hold our haxe source code)
  - copy your `package.json` file
  - make a folder called `.haxelib/` this is like `node_modules` but for haxe

- Then we’re going to try haxe hello-world to check everything works:

In `src/Main.hx` add the folloing:

```haxe
function main() {
    trace('hello world!');
}

```

In `build.hxml` add

```hxml
# tell haxe to look in the src directory for source code
--class-path src
# set the entry point to our Main file
--main Main
# set dead-code-elimination to full for cleaner js code
--dce full
# generate javascript output
--js bin/index.js

```

Now we’re ready to test. Open this directory in vscode with the [haxe plugin](https://marketplace.visualstudio.com/items?itemName=nadako.vshaxe) installed. Compile the program using _Terminal_ → _Run Build Task_. Alternatively, on the command-line run `haxe build.hxml`.

This will create a new file: `bin/index.js` that will contain your generated javascript. Run it with  
`node bin/index.js`. It should return

```haxe
src/Main.hx:2: hello world!

```

## Porting Node.js Server Code

To use the node.js APIs we first need the node.js haxe externs. From the command line run:

```haxe
haxelib install hxnodejs

```

This will install the files into that `.haxelib/` folder we created earlier

Next to tell haxe it can use this library when compiling, add `--library hxnodejs` to build.hxml. You can add on any line but I recommend adding it at the top of the file

Now we can try to use the node.js API to make a minimal web server. I am translating the [node.js getting-started example](https://nodejs.org/en/docs/guides/getting-started-guide/).

In JavaScript this looks like so:

```javascript
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

```

We can almost copy and paste this into Main.hx, but we need to make some changes:

- In haxe we only use `import`, so `const http = require('http');` becomes `import js.node.Http;`
- In haxe `const` is `final`
- Arrow functions use `->` rather than `=>`
- for `console.log` we can use `trace`
- Haxe doesn’t have backtick strings ` (it doesn’t need them; regular strings have always allowed for multi-lines. Replace those with single-quotes which enables [string interpolation](https://haxe.org/manual/lf-string-interpolation.html)
- Finally, haxe requires an entry point function called `main`, whereas javascript doesn’t. So we want to put our startup code in there.

Back in our `src/Main.hx`, we can replace it with the following:

```haxe
import js.node.Http;

final hostname = '127.0.0.1';
final port = 3000;

final server = Http.createServer((req, res) -> {
	res.statusCode = 200;
	res.setHeader('Content-Type', 'text/plain');
	res.end('Hello World');
});

function main() {
	server.listen(port, hostname, () -> {
		trace('Server running at http://${hostname}:${port}/');
	});
}

```

Compile again (_Terminal_ → _Run Build Task_ or run `haxe build.hxml`)

Now we can test our server:

`node bin/index.js`  
src/Main.hx:32: Server running at [http://127.0.0.1:3000/](http://127.0.0.1:3000/)

Opening [http://127.0.0.1:3000/](http://127.0.0.1:3000/) should show `Hello World`

Here is a working example: [https://github.com/haxiomic/dts2hx/files/6255393/haxe-server-example.zip](https://github.com/haxiomic/dts2hx/files/6255393/haxe-server-example.zip)

When porting, you can use autocomplete to help you figure out where the node.js APIs are – just start typing the name of the API you want to use (e.g. ‘http’) and it will suggest `js.node.Http` (among others)

## Using a node.js library: express

If you use a framework like express, you’ll want to get externs for those too. This is the same process that typescript uses, but we need to convert the typescript externs to haxe with a tool called [dts2hx](https://github.com/haxiomic/dts2hx). To install express and the express externs, you can run the following commands:

```haxe
npm install express 
npm install @types/express
npm install dts2hx
npx dts2hx express

```

This will install express externs to `.haxelib/`. Again add `--library express` to the top of `build.hxml` so we can use the externs.

Now we’re ready to write a webserver using express, here’s a basic example, you can read more about how this example was ported in this thread [How does one use Routes in Express?](https://community.haxe.org/t/how-does-one-use-routes-in-express/2701)

```haxe
final app = Express.call();
final port = 3000;

final router = express.Router.call_();

function main() {
	app.get('/', (req, res, next) -> res.send('Hello World! <a href="/birds">/birds</a>'));
	app.listen(port, () -> trace('Example app listening at http://localhost:${port}'));

	app.get('/route', (req, res, next) -> res.send('Example route'));

	// middleware that is specific to this router
	router.use(function timeLog (req, res, next) {
		trace('Time: ' + Date.now());
		(next: () -> Void)();
		return null;
	});

	// define the home page route
	router.get('/', (req, res, next) -> {
		res.send('Birds home page');
	});

	// define the about route
	router.get('/about', (req, res, next) -> {
		res.send('About birds');
	});

	app.use('/birds', router.call);
}

```

For other libs you can use a similar process so long as typescript externs are available, however if they’re not available and you don’t want to make them yourself, you can call javascript code directly.

## Calling js code without externs

For example, say we want to call `console.log`. There are externs defined for this (`Node.console.log('hello');`) but say there weren’t. We can use the `untyped` keyword to disable typing:

```haxe
untyped {
  console.log('hello');
  console.error('example');
}

```

To use `require()` directly, we can do

```haxe
final http = js.Lib.require('http');

```

(or use untyped like before)

Or to inject raw javascript, you can write

```haxe
js.Syntax.code('console.log("hello");');

```

Life is a lot nicer if you have or [write externs](https://haxe.org/manual/lf-externs.html) but these options can save you some time while porting

Good luck! Let me know how you get on!

---

_[View the full topic](https://community.haxe.org/t/nodejs-to-a-web-app/2967)._
