I need to write a server in TypeScript and Node.
The result is:
/// <reference path="definitions/commonjs.d.ts" />
/// <reference path="definitions/node.d.ts" />
var http = require("http");
namespace MyProj {
export class Server {
public run() {
var server = http.createServer(); // TypeScript does not recognize 'http'
}
}
}
But I cannot understand how I can reference the http
module. Where can I find the types? In the definition file i am having hard time recognizing this information.
The http requests in TypeScript can be placed using a function called fetch() function. The fetch() function takes two parameters, namely URL and options and returns a Response object.
TypeScript is well-established in the Node. js world and used by many companies, open-source projects, tools and frameworks. Some of the notable examples of open-source projects using TypeScript are: NestJS - robust and fully-featured framework that makes creating scalable and well-architected systems easy and pleasant.
Node. js has a built-in module called HTTP, which allows Node. js to transfer data over the Hyper Text Transfer Protocol (HTTP). To include the HTTP module, use the require() method: var http = require('http');
One of the best things about Node.js is its massive module ecosystem. With bundlers like webpack we can leverage these even in the browser outside of Node.js. Let’s look at how we can build a module with TypeScript usable by both JavaScript developers and TypeScript developers.
A starter template for TypeScript and Node with a detailed README describing how to use the two together. - Microsoft/TypeScript-Node-Starter Seems like you may need to add "module": "commonjs", into your tsconfig if you’re missing it import * as http from "http"; + the config is what’s necessary 99% of the time I’ve had issues
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP). To include the HTTP module, use the require () method: The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.
If you want to use the axios package to make Http requests in TypeScript, check out my other article - Making Http requests with Axios in TypeScript , as this article uses the built-in fetch method. At the time of writing you have to install the node-fetch package if you're running your code in Node.js.
It's because of you are using require
. use import
instead it will recognize and also will give you nice intellisense :-)
import * as http from "http"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With