Cannot find module - node.js

I have a class that I have created and put it in a custom folder in the src folder. It is not a nestjs module nor a provider just a helper class that I can instantiate and use. However when I run the app I got the following error:
npm run start:dev
> rent-go#1.0.0 start:dev /Users/arsenegandote/Applications/js/rent-go
> nodemon
[nodemon] 1.18.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: /Users/arsenegandote/Applications/js/rent-go/src/**/*
[nodemon] starting `ts-node -r tsconfig-paths/register src/main.ts`
Error: Cannot find module './json.result.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:603:15)
at Function.Module._resolveFilename (/Users/arsenegandote/Applications/js/rent-go/node_modules/tsconfig-paths/lib/register.js:75:40)
at Function.Module._load (internal/modules/cjs/loader.js:529:25)
at Module.require (internal/modules/cjs/loader.js:658:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (/Users/arsenegandote/Applications/js/rent-go/src/lib/api.controller.ts:1:1)
at Module._compile (internal/modules/cjs/loader.js:722:30)
at Module.m._compile (/Users/arsenegandote/Applications/js/rent-go/node_modules/ts-node/src/index.ts:439:23)
at Module._extensions..js (internal/modules/cjs/loader.js:733:10)
at Object.require.extensions.(anonymous function) [as .ts] (/Users/arsenegandote/Applications/js/rent-go/node_modules/ts-node/src/index.ts:442:12)
[nodemon] app crashed - waiting for file changes before starting...](url)
This is the generic class I am instantiating in a controller:
export class JsonResult<T> {
readonly status: string;
readonly data: T;
constructor(status: string, data: T) {
this.status = status;
this.data = data;
}
}
And my controller implements this abstract class:
export abstract class ApiController {
failed(): void {
throw new HttpException(
{
status: ApiStatus.FAILED,
data: {},
},
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
notFound(): void {
throw new HttpException(
{
status: HttpStatus.NOT_FOUND,
data: [],
},
HttpStatus.NOT_FOUND,
);
}
badRequest(message: string): void {
throw new HttpException(
{
status: HttpStatus.BAD_REQUEST,
data: {
message,
},
},
HttpStatus.BAD_REQUEST,
);
}
success<T>(data: T): JsonResult<T> {
return new JsonResult<T>(ApiStatus.SUCCESS, data);
}
}

Error: Cannot find module './json.result.js'
The error means that your file cannot be found. Make sure your import path is correct.

Related

i cannot declare new property in request object of express

I'm trying to attach the new property to the request object in typescript.
this is the code :
import { request, Request, response, Response } from "express";
((req: Request, res: Response) => {
console.log(req.user);
})(request, response)
i'm declaring like this :
declare global {
namespace Express {
interface Request {
user: string;
}
}
}
and then I'm running it with ts-node. result is :
/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:843
return new TSError(diagnosticText, diagnosticCodes, diagnostics);
^
TSError: тип Unable to compile TypeScript:
x.ts:9:21 - error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
9 console.log(req.user);
~~~~
at createTSError (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:843:12)
at reportTSError (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:847:19)
at getOutput (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1057:36)
at Object.compile (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1411:41)
at Module.m._compile (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1596:30)
at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Object.require.extensions.<computed> [as .ts] (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1600:12)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:827:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
diagnosticCodes: [ 2339 ]
}
I tested too many answers of sites, but one of them did not work. please help.
First, I think your declare file got some problems.
edit the file like
export {}
declare global {
namespace Express {
interface Request {
user: string;
}
}
}
or
namespace Express {
interface Request {
user?: string
}
}
add directory that contains the declare file in tsconfig. Since I usually name it express.d.ts and place in src/types folder, in my case, tsconfig.json will be edited like this
{
"compilerOptions": {
"typeRoots": ["src/types"],
}
}
lastly, also add ts-node configuration in tsconfig.json. (not in compilerOptions)
{
"ts-node": {
"files": true
}
}
Are you maybe looking for #types/express ?
You can also fix it with intersection type :
function endpoint (req: Request, res: Response & {user: string;}) {
console.log(req.user);
}
But maybe you are looking for req.body.user, type Response<{user: string;}> ?

ts-node cannot find npm module discord-api-types

When attempting to run discord.js file deploy-commands.ts with the command ts-node deploy-commands.ts ts-node produces the following error:
Error: Cannot find module 'discord.js/node_modules/discord-api-types'
Require stack:
- /Users/Cameron/discord.js/discordjs-guides/deploy-commands.ts
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/usr/local/lib/node_modules/ts-node/node_modules/#cspotcode/source-map-support/source-map-support.js:679:30)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/Cameron/discord.js/discordjs-guides/deploy-commands.ts:4:1)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1455:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:1458:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/Users/Cameron/discord.js/discordjs-guides/deploy-commands.ts' ]
}
Despite discord-api-types appearing both in the node-modules folder and in package.json. The error is consistently reproduced after running npm install discord-api-types and npm resoding discord-api-types is up-to-date.
Package.json dependencies:
"dependencies": {
"#discordjs/builders": "^0.12.0",
"#discordjs/rest": "^0.3.0",
"discord-api-types": "^0.29.0",
"discord.js": "^13.6.0",
"dotenv": "^16.0.0",
"nodemon": "^2.0.15",
"ts-node": "^10.7.0"
}
deploy-commands.ts:
import { SlashCommandBuilder } from "#discordjs/builders";
import { REST } from "#discordjs/rest";
import { version } from "discord.js";
import { Routes } from "discord.js/node_modules/discord-api-types";
const { token, guildID, clientID } = require('./process.json')
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong.'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info.'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user info.'),
]
.map(commands => JSON)
const rest = new REST({version: '9'}).setToken(token)
rest.put(Routes.applicationCommand(clientID, guildID), {body: { commands }})
.then(() => {
console.log('Successfully registered application commands')
})
.catch(console.error)
I think you need to change this code line:
import { Routes } from "discord.js/node_modules/discord-api-types";
To its version using because of this:
const rest = new REST({version: '9'}).setToken(token)
So you need to define the version you use, try changing your import to
import { Routes } from "discord-api-types/v9";
As I tried to my testing slash command files, you can do this kind of line too:
import { Routes } from "discord.js/node_modules/discord-api-types/v9";
I'm not using .ts so might not work but give it a shot

How to bundle worker_thread dependencies with webpack

I'm writing an electron application that uses electron forge for setup and configuration.
The project uses Webpack 5 as a bundler and typescript as the development language. I'm having trouble running a worker_thread on the main-thread.
It all works fine, as long as the worker_thread does not use any imported local modules. But when I import modules they can't be found. I'm thinking this is because webpack doesn't bundle the dependencies from the worker.
My code looks like this:
index.ts (electron main thread):
ipcMain.handle('export', async (event, measurements: Measurement[], options: ExportOptions) => {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./export.worker.js', import.meta.url))
worker.on('message', resolve)
worker.on('error', reject)
worker.postMessage({
measurements,
options,
})
})
})
export.worker.js (same folder as main.ts):
const { parentPort } = require('worker_threads')
const { Export } = require('../preload/export')
parentPort.on('message', async (data) => {
const { measurements, options } = data
await Export.export(measurements, options)
parentPort.close()
})
When I try to run this I get:
Error occurred in handler for 'export': Error: Cannot find module '../preload/export'
Require stack:
- C:\Development\spectro-demo\internal-client\.webpack\main\a3142abb2db60e4fab06.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:892:15)
at Function.Module._load (internal/modules/cjs/loader.js:737:27)
at Module.require (internal/modules/cjs/loader.js:964:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Development\spectro-demo\internal-client\.webpack\main\a3142abb2db60e4fab06.js:2:20)
at Module._compile (internal/modules/cjs/loader.js:1083:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1113:10)
at Module.load (internal/modules/cjs/loader.js:940:32)
at Function.Module._load (internal/modules/cjs/loader.js:781:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Development\\spectro-demo\\internal-client\\.webpack\\main\\a3142abb2db60e4fab06.js'
]
}
So I'm wondering: How can I use worker_threads that reference modules in my project?
I was able to fix it. Seems to be a bug in webpack 5. See this repo for a workaround: https://github.com/DustinJSilk/web-worker-ts-webpack-test

Encrypt pdf file using node-qpdf

I am trying to use node-qpdf
I just did simple:
Test.pdf is inside directory where index.js is
var qpdf = require('node-qpdf');
var options = {
keyLength: 128,
password: 'test123',
restrictions: {
print: 'low',
useAes: 'y'
}
}
var localFilePath ='Test.pdf';
var outputFilePath ='test';
qpdf.encrypt(localFilePath, options, outputFilePath);
I am getting error like:
Run: nodemon index.js
[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
C:\Users\Rad\Desktop\node-qpdf-master\test\node_modules\node-qpdf\index.js:56
return callback(null, outputStream);
^
TypeError: callback is not a function
at Object.Qpdf.encrypt (C:\Users\Rad\Desktop\node-qpdf-master\test\node_modules\node-qpdf\index.js:56:16)
at Object.<anonymous> (C:\Users\Rad\Desktop\node-qpdf-master\test\index.js:13:6)
at Module._compile (internal/modules/cjs/loader.js:945:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
at Module.load (internal/modules/cjs/loader.js:798:32)
at Function.Module._load (internal/modules/cjs/loader.js:711:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:1014:10)
at internal/main/run_main_module.js:17:11
[nodemon] app crashed - waiting for file changes before starting...
I think they haven't updated the docs, I read their codes, you must put outputFile and change your options into like this.
var options = {
keyLength: 256,
password: '12345',
outputFile: '<your output name file>',
restrictions: {
modify: 'none',
extract: 'n'
}
var doc = await qpdf.encrypt(`${fileLocation}.pdf`, options)

How to lint a typescript types file?

are there any ways to lint or otherwise debug a types file?
I have a index.d.ts file of all my types, but it seems to crash my app at startup.
using tsc with some basic options works fine
using tslint works fine.
but when running with the webpack compiler I get the following error.
the file contents are a lot but basically like the below.
I had some issues with exporting enums before but basically not getting any actual errors I can understand.
// we SEND to Boto
export enum MsgTypeOut {
TEXT = 0,
IMAGE = 1,
URL_LINK = 2,
FILE = 3,
}
export interface BotoTextMsg {
chatId: string
messageType: MsgTypeOut.TEXT
token?: string
payload: {
text: string
}
}
nodemon:watch early exit on watch, still watching (1) +14s
/Users/dc/dev/tix/recobot/stack/backend/server.js:2663
throw new Error("Module build failed: Error: Typescript emitted no output for /Users/dc/dev/tix/recobot/stack/shared/typezoo/index.d.ts.\n at successLoader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:47:15)\n at Object.loader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:29:12)");
^
Error: Module build failed: Error: Typescript emitted no output for /Users/dc/dev/tix/recobot/stack/shared/typezoo/index.d.ts.
at successLoader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:47:15)
at Object.loader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:29:12)
at Object.__awaiter (/Users/dc/dev/tix/recobot/stack/backend/server.js:2663:7)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.defineProperty.value (/Users/dc/dev/tix/recobot/stack/backend/server.js:2551:19)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.__awaiter (/Users/dc/dev/tix/recobot/stack/backend/server.js:867:16)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/server.js:1306:18)
at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/server.js:1343:30)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.__awaiter (/Users/dc/dev/tix/recobot/stack/backend/server.js:1028:15)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.defineProperty.value (/Users/dc/dev/tix/recobot/stack/backend/server.js:63:18)
at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/server.js:66:10)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
[nodemon] app crashed - waiting for file changes before starting...
webpack config is pretty much vanilla based on create-react-app.
const fs = require("fs")
// const path = require("path")
const NodemonPlugin = require("nodemon-webpack-plugin");
const nodeModules = {};
fs.readdirSync("node_modules")
.filter(function (x) {
return [".bin"].indexOf(x) === -1;
})
.forEach(function (mod) {
nodeModules[mod] = "commonjs " + mod;
});
module.exports = {
entry: "./server/server.ts",
output: {
filename: "server.js",
// path: path.join(__dirname, "/build"),
},
externals: nodeModules,
// needed to fix https://github.com/webpack/webpack/issues/1599
node: {
__dirname: true
},
module: {
loaders: [
{
loader: "ts-loader",
test: /\.tsx?$/,
},
],
},
plugins: [new NodemonPlugin()],
resolve: {
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"],
},
target: "node",
};
For anyone watching, the error is related to importing enums.
You can export an enum from a types.d.ts file... but it won't import and blows up in this weird way.
https://lukasbehal.com/2017-05-22-enums-in-declaration-files/
How to refer to Typescript enum in d.ts file, when using AMD?

Resources