require('fs') not working with angular and electron - node.js

I am using angular 6.0, electron 2.0, typescript 2.9, nodejs 9.11 to make a desktop app using electron framework. I am struggling with accessing NodeJS native API from the typescript code. I have set "commonjs" in the "tsconfig.app.json" file. When I write : require('fs') or require('net') in any of the ts files which are part of angular application, the system isn't able to find those modules.
Only one solution has worked so far. It goes like this. First in 'native.js'
window.fs = require('fs')
Then in polyfill.ts :
declare global {
interface Window{
fs : any;
}
}
Then access fs in the rest of codebase as window.fs.
While this is okay, but it is not scalable as if I have to use any library which depends on NodeJS native API, then that library has to be imported through this mechanism.
Is there any other solution to let angular allow importing of nodejs system libraries through normal require(<module>) syntax?

import * as Fs from 'fs';
const fs: typeof Fs = window['require']('fs');

on my side, this work if you use typescript for ref.
You need give a defenition or is will any.
Using this for nwjs, know nodejs is global.
const fs: typeof import('fs') = require('fs');

Related

Prevent webpack from removing crypto in nodejs API

I have a node-js API that's part of an nx workspace and I'm trying to use the core crypto node-js module, however I think it's getting stripped out by webpack.
My code uses the following:
crypto.getRandomValues(new Uint32Array(1))[0].toString(16)
However I get a runtime error:
ReferenceError: crypto is not defined
Am I right in thinking this issue is likely being caused by webpack? And if so, how can I use crypto in my API?
I'm very new to webpack, so I'm pretty clueless here. My nx project uses the #nrwl/node:webpack executor (the default for node-js APIs), and I've followed the steps here on how to customize this projects webpack configuration, so my custom webpack config is being used, I just dont know what to do with it on order to allow my API to use crypto.
Any help on this would be appreciated.
For completeness, here's what my custom webpack config looks like, but it makes no difference to the problem. Note that his was crafted based on some of the suggested answers here:
const { merge } = require('webpack-merge');
/** #type { import('webpack').Configuration } */
const webpackConfig = {
target: 'node',
resolve: {
fallback: {
"crypto": false
}
}
};
module.exports = (config, context) => merge(config, webpackConfig);
Edit: As a workaround, I've imported the randomUUID function from crypto and can use this to do what I need to do. It seems having this import means crypto gets included in the webpack.
import { randomUUID } from 'crypto';
randomUUID().split('-')[0];
In your above code + runtime error, it seems like you haven't imported crypto correctly.
Furthermore you are mixing up some concepts. Webpack is normally used for frontend projects, as Node.js supports requiring modules out of the box and you don't need to compile your code, as you don't need to generate a javascript bundle that's servable by browsers.
Because your project runs in the browser, but your tests run in Node, which has a different global namespace, you get issues. In the browser crypto is defined globally, but in Node you need to import the crypto standard library, the "suggested answers" you are linking to talks about this concept.
To fill in the gap between browser and Node, to ensure the code you write works for test + browser, you use polyfills.
In your usecase you have a Node.js project. Crypto is a standard library for Node.js and you can just require it, why should you configure webpack to create fallbacks for it or use polyfills?

Swagger generate Node.JS Express server code

I have Swagger 2.0 documentation, and I would like to create a Node.JS server stub from the existing Swagger spec.
When I use the Swagger Editor, it has the option to generate Node.js server stubs, but the generated file uses the connect NPM libraries.
I would prefer to use Express, and have the application folder structure of a general Express application. Is there a way to modify the generation of the Node.JS server stub to be compatible with Express?
The easy answer is to change var app = require('connect')(); to var app = require('express')(); in nodejs-server-server/index.js. But it's not optimal since the generated code does not take use of the functionality of Express.
It seems like there will be a express code generator in the next version of swagger-codegen.
You could also use swaggerize-express to do the server stub generation.

Using Vue JS with Require JS?

I installed the following via Bower:
jQuery 3.1.0
Vue 1.0.26
Require.js 2.2.0
But when I load my site, "Vue" is undefined.
I tried var vue = require('Vue') and stuff, but it doesn't seem to work.
Vue says it is a AMD module and so is Require.js... What am I missing?
var vue = require('Vue') won't work by itself. Either you:
Change it to the form of require that takes a callback:
require(['Vue'], function (vue) {
// code that uses Vue
});
Or put your require call in a define call:
define(function (require) {
var vue = require('Vue');
});
As Linus Borg pointed out, require with a single string is CommonJS syntax, which RequireJS supports only if it appears in the callbacks passed to define. (See this.)

Express 4.x with Typescript

I am trying to make a express app with typescript.
This is my code so far:
//<reference path="./server/types/node.d.ts"/>
//<reference path="./server/types/express.d.ts"/>
import express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('hi');
});
app.listen(3000);
nothing really shocking, I am just trying to make this work, but somehow, always when I try translate this file to a js file. I get strange errors, even if I change the express version to 3.1 (the express.d.ts is just supported for express 3.1 not for 4.x)
Any idea, where I can get a express.d.ts file for express 4.x or what I am doing wrong?
>> error TS2071: Unable to resolve external module ''express''
>> error TS2071: Module cannot be aliased to a non-module type.
>> error TS2095: Could not find symbol 'express'.
You reference comments are wrong. There needs to be three slashes /// :
///<reference path="./server/types/node.d.ts"/>
///<reference path="./server/types/express.d.ts"/>
The only way you can get that error if you are using this reference file https://github.com/borisyankov/DefinitelyTyped/blob/master/express/express.d.ts#L26 was that your reference comments were wrong and typescript was not reading that express.d.ts :)
Might I add that because you are using express 4.x and the type definitions are not up-to-date, you will be missing some key features that are central to express 4.x, such as Routers.
You have two choices at this point: update the type definitions, or use
var express = require('express');
instead, which removes some of the benefits that typescript provides, but is something you're bound to run into in the future with other node modules, such as mongoose.

Using Express() with TypeScript

I want to use the most recent version of Expess with node.js in TypeScript. The express.d.ts provided by microsoft in the samples seems to be built upon a versions prior to 3.0.x.
In previous version you could do
var app = express.createServer()
but after 3.0.x you should do:
var app = express();
Express.d.ts does not support this... I've found a hack around this:
I've added the following line to Express.d.ts:
export function(): any;
In app.ts when I want to create the app object I do the following:
var app = <express.ExpressServer>express();
This seems to fix the issue, it's compiling without an error, and also I get intellisense support. However this is a hack... First of all why can't I write something like this?
export function(): ExpressServer;
Is this the recommended way to fix this issue?
Pretty old discussion, but I ran into the same problem recently and found that there is a new express.d.ts that properly supports express 3 on the DefinitelyTyped site.
You should be able to add this ambient function declaration to express.d.ts to get what you want.
declare function express(): ExpressServer;
if you declare express this way: import * as express from "express", you will get this error in runtime, declaring it this way: const express = require "express", won't throw any error.
Also, don't forget to declare app variable or property type as express.Application
Here's a sample project - Express 4.x app in TypeScript: https://github.com/czechboy0/Express-4x-Typescript-Sample

Resources