why module.export { ...require('module') } work but not module.export { require('module') } - node.js

justExport.js
const first = () => {
console.log('frist from justExport')
}
const second = () => {
console.log('second fromt justExport')
}
module.exports = {
first,
second,
}
tmp.js
module.exports = {
...require('./justExport') // work
require('./justExport') // SyntaxError: Unexpected string
}
main.js
const justExport = require('./justExport.js')
const tmp = require('./tmp.js')
console.log('Hello World!')
I have voluntarily create a fake example with the less possible code.

{ ...require('./justExport') } is object literal spread. While { require('./justExport') } is incorrect object literal syntax because it doesn't contain a key.
Unless the intention is to create shallow copy of justExport module, object literal isn't needed. It can be:
module.exports = require('./justExport');

To further clarify the answer from #estus, note that the following works due to ES6 shorthand property names:
const justExport = require('./justExport');
module.exports = {
...justExport, // works
justExport // works because key is implicitly defined by variable name
}

Related

how to refer to a function when unit testing with NodeJS / Mocha

I'm making my first test with Mocha.
Dummy test is passing, but when I want to refer to my actual function that is in another file, it won't find it:
ReferenceError: main is not defined
I have a single index.js with :
async function main() {
function comparer(otherArray) {
return function (current) {
return otherArray.filter(function (other) {
return other.prm === current.prm && other.conso_prod === current.conso_prod
}).length === 0;
}
}
}
module.exports = main();
and in my test.js file, I do:
const {expect} = require('chai');
describe('Sum numbers', () => {
it('Compare 2 existing array', () => {
const meters = []
const perimeter = []
const onlyInMeters = meters.filter(main.comparer(perimeter));
expect(onlyInMeters).to.equal([]);
});
});
But when I refer to main.comparer, it can't find it:
ReferenceError: main is not defined
What am I forgetting? Sorry, I'm a NodeJS Noob!
It seems like you did not import the index.js file in test.js file. You are returning noting from main function as well.
Also, why are you exporting it like module.exports = main(); Instead you can do this:
// index.js
module.exports = {
comparer: (otherArray) => { ... }
}
// test.js
cosnt main = require('PATH_OF_index.js');
main.comparer();

webpack require expression missing modules

From webpack documentation, when a require expression is not known at compile time, it should generate a context module and include all the modules that could match the expression.
const handlers = {};
for (const name of Object.keys(SomeObject)) {
try {
handlers[name] = require(`./${name}.js`);
} catch {} // eslint-disable-line no-empty
}
module.exports = handlers;
however, what I get is `
const handlers = {};
for (const name of Object.keys(SomeObject)) {
try {
handlers[name] = require(`./${name}.js`);
} catch {} // eslint-disable-line no-empty
}
module.exports = handlers;
however, what I actually get is this error Cannot find module ./\u001a.js
but if I turn it into a dynamic import expression then it works
const handlers = {};
for (const name of Object.keys(SomeObject)) {
try {
import(`./${name}.js`).then(m => { handler[name] = m; });
} catch {} // eslint-disable-line no-empty
}
module.exports = handlers;
But I would prefer not to do that since the offending code is from some node package

testing an actual returning value on javascript using jest

I have the following js function:
const modelUtils = {
modelingObj(obj, stringVal = ‘RE’) {
let newObj;
//my logic for setting value of newObj
return newObj;
};
export default modelUtils;
I want to test and see that based on a specific params I get a particular result, the issue is I’m always returning back an empty object.
Test.js
import modelUtils from '../modelUtils';
jest.unmock('../modelUtils');
describe(' testing modelUtils', () => {
let test;
const mockData = {
myProperty: [],
};
describe('testing modelingObj function', () => {
it('For my first test’, () => {
test = modelUtils.mockData, ‘TR’);
expect(test).toEqual({ myProperty: [] });
});
});
});

node.js adding new export field without braking existing requires

Consider following simple scenario, file config.js:
const config = {
a: '123'
}
module.exports = config;
and it's usage:
const cfg = require('./conifg');
console.log(cfg.a);
Now I'm in need to add additional export member to config.js:
const config = {
a: '123'
}
function someFunction() {
console.log('blah');
}
module.exports = {
config,
someFunction
};
This modification brakes down so-far working code, because cfg.a in
const cfg = require('./conifg');
console.log(cfg.a);
points now to undefined.
Is there any way to extend module.exports while remaining it's "default" exported member to not brake things down?
you may export all property of config separately
module.exports = {
...config,
someFunction
};
or if you don't want use spread, you can access by
const cfg = require('./conifg');
console.log(cfg.config.a);
You can do it like this
const config = {
a: '123',
someFunction: someFunction
}
function someFunction() {
console.log('blah');
}
module.exports = config;

How to override a method in Node.js?

I have a module that defines functions that will be shared by other modules. Some of those functions need to be overridden. This is what I was thinking, but it doesn't work:
// shared_module.js
module.exports = {
alternativeFun() {
exports.doSomething()
sharedFun()
},
sharedFun() {
console.log('shared')
}
}
// alternative_module1.js
module.exports = {
doSomething() {
console.log('alternative 1')
}
}
// alternative_module2.js
module.exports = {
doSomething() {
console.log('alternative 2')
}
}
// main.js
const shared1 = require('./shared_module')
shared1.doSomething = require('./alternative_module1').doSomething
shared1.alternativeFun()
const shared2 = require('./shared_module')
shared2.doSomething = require('./alternative_module2').doSomething
shared2.alternativeFun()
Setting module.exports does not magically change the value of exports. You will need to also assign it to the same value (module.exports = exports = ...) if you want to use it inside your module's functions.

Resources