2

I have a typescript file in which some functions have been added. The following shows the actual address of the typescript file :

../myproject/src/util/validation/user-validation

All the functions are exported from the file. For instance,

export function validateSignUpData(userDetail:UserDetail):Array<String>{

    let errorMessages = new Array<String>();
    /* Some Code */

Now I am trying to use the exported function in Node server, though it throws an error which I do not comprehend.

Error: Cannot find module '../myproject/src/util/validation/user-validation'

This is how I tried to get the functions inside my Node server file:

app.post('/users',(req,res)=>{

    let validator = require('../myproject/src/util/validation/user-validation');
    let errorMessages = validator.validateSignUpData(req.body);

I googled require function, and it seemed that my code must work properly. Some forums suggests that typescript must be installed to resolve the issue, though I have already installed typescript!

I will be glad, if you help me! Thank you.

Retro Code
  • 125
  • 8

2 Answers2

0

There are 2 methods of modules in node js, es6 modules and requrejs

require is used together with module.exports add this to your module module.exports.validateSignUpData=validateSignUpData and then the require function will export it.

The other way is to use es6 modules but it doesn't work under all circumstances https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_enabling

Jew
  • 476
  • 2
  • 8
  • 1
    Uhhh, ES6 modules are supported in node. Not sure that has anything to do with the OP's question, but thought I should correct that statement in your answer. – jfriend00 Mar 01 '20 at 18:39
0

The export keyword is used for ES6 modules (Related article also covering node.js). This is a new language feature that was shipped in 2015.

It uses export function name() {...} to export a function and import {name} from './path/to/file'; to import it somewhere else.

Node uses the CommonJs syntax (which is still largely popular).

The idea behind it is that any module (i.e. js-file) can export an object like this: module.exports = {key: "value"}. This object can then be imported using require('./path/to/file').

You can use es6 modules in node like this: How can I use an es6 import in node?.

Max
  • 620
  • 4
  • 22