Programming Node.js app. with TypeScript



Resources
Settings

TypeScript imposes the installation of Node.js types as dev. dependency

npm i @types/node --save-dev

Resulting package.json file

{
  "author": "FranckBarbier.com",
  "description": "Image snapshot",
  "license": "MIT",
  "main": "js/Main.js",
  "name": "Save_image_from_URL.Node.js.ts",
  "version": "1.0.0",
  "scripts": {
    "configuration": "tsc --showConfig",
    "compilation": "tsc",
    "execution": "node js/Main.js"
  },
  "devDependencies": {
    "typescript": "^5.1.3",
    "@types/node": "^18.16.18"
  }
}
Programming

Library import can then be ruled from TypeScript (Save_image_from_URL.ts file)

import * as file_system from 'fs'; // https://nodejs.org/api/fs.html
import { IncomingMessage } from 'http'; // https://nodejs.org/api/http.html
import * as https from 'https'; // https://nodejs.org/api/https.html

const Save_image_from_URL = function () {
    https.get('https://i5.walmartimages.ca/images/Large/912/760/6000197912760.jpg', (response: IncomingMessage) => {
        response.pipe(file_system.createWriteStream('./Nutella.jpg'));
    });
};

export default Save_image_from_URL;

Import of user-defined stuff (Main.ts file)

import Save_image_from_URL from './Save_image_from_URL'; // Import of user-defined stuff...

console.log(typeof Save_image_from_URL); // 'function' is displayed

Save_image_from_URL(); // Image snapshot...
Exercise