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.
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
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 (ie 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? .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.