Cannot import module 'os' in Electron

Viewed 778

I am doing an easy test to try to get my computer's name in an Electron app using Angular and nodejs.

This is my script:

import { Component, OnInit } from '@angular/core';
import { hostname } from 'os'

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
    console.log(hostname);
  }

}

I also installed npm i @types/node

I get the following error:

Error: src/app/components/home/home.component.ts:2:26 - error TS2307: Cannot find module 'os' or its corresponding type declarations. import { hostname } from 'os'

Any ideas? this should be straightforward and I feel so silly with such a problem...

Edit: I added that this is an electron app!!

4 Answers

Before using import * as os from 'os';, you have to make sure "types":["node"] in the tsconfig.app.json

{
  "compilerOptions": {
    "types": [
      "node"
    ]
  }
}

I didn't read his question properly.

the commenter is right you cannot import os to do this on an angular client side application.

instead it should be no imports and you can access via the document, or the window.

USING DOCUMENT

document.location.hostname

or

USING WINDOW

 window.location.hostname

this is rather unbelievable but without ActiveX controls it won't work and even then it will work very little because almost all windows based pc's have this disabled by default I believe.

its easy to get the client IP address - but this gets incredibly complex. You can try http interceptor but that seemed like it was half baked based upon the three hours of my life I dedicated to this. I'm rather dumb founded to be honest.

The correct code is

import * as os from 'os';

Usage example :

const hostname = os.hostname();
Related