How do you export an object in a module in nodejs? - node.js

There is something wrong with the way I understand how to use classes in a Javascript module and export them, or some bad assumption I made about how nodejs works. Please help me understand this better. I wanted to write a module that exposed an object that will "store things safely." I have a file ("safestore.js") with this in it:
class Safestore {
constructor() {
console.log("SUCCESS!");
}
... // I defined other methods here...
}
exports.safestore = Safestore; // I tried this with `new Safestore` and `new Safestore()` too.
I run nodejs on my command line and then:
> ss = require('./safestore');
{ safestore: [Function] }
> s = ss.safestore('pwd','./encFile.enc');
ReferenceError: Safestore is not defined...
Why is it telling me that Safestore is not defined while executing the safestore function which is defined in the same file where Safestore is, actually defined?

The question does not contain enough information, although there is a clue. node and nodejs are two different pieces of software, and I was using the wrong one. I also didn't specify what version of nodejs I ran from my command line. When I ran it with node (instead of nodejs) I got errors that made sense and I was able to fix them.
Thanks to #Ethicist for listing the version of Node he used, as this got me to double check all those things.
I just need to remember that node and nodejs each do different things. Further research shows me that nodejs is a symlink to version 8.10.0 of node.js, and node is a symlink to the version that I set with nvm. I solved the problem permanently for myself with sudo rm /user/bin/nodejs and I'll remember, if I ever see an error that says nodejs doesn't exist, that it wants the old version of node.js.

Related

Node JS: How to check if a dependent application is installed on target machine?

I would like to implement an external dependency validation logic in my Node JS console application. For example, git. In the terminal "git --version" would respond with current version of the git installed. I might use child_process module in Node and invoke shell commands but is there a better way to do it? It should work regardless of the host operating system.
Why Am I having such requirement?
My application should create a git like merge conflict if 2 or 3 versions (Modified, Original, Remote) of the file having conflicting changes. I wish I could use some node modules to achieve. But it turns that there is none. So I decided to use 'git merge-file'. But before executing the command, I would want to check if git is installed or not. This might seem odd but your suggestions are valuable. Thanks in advance.
Child process is the solution you should go for, as you have already figured it out. It's the only way to interact with other processes from Node.js application.
You can have something like:
const { exec } = require('child_process');
exec('git --version', error => {
if (error) {
// Git doesn't exist
// Add your handler code here
}
else {
// Git exists
// Add remaining of code here
}
});

Using require within an NPM package

I've written a custom NPM package that will spin up a mocked Apollo GraphQL server for me with some custom settings.
In my /bin folder I have a file, server.js which is responsible for spinning up the server.
In package.json I've set up my command like this:
...
"bin": {
"mock-server": "./src/server.js"
},
...
So when I run the command mock-server from the parent project it will execute the server.js file.
All good so far, but the problem is that once I start trying to require dependencies I run into this error:
$ use-env mock-server
/Users/dev/projects/share-vde-frontend/node_modules/.bin/mock-server: line 1: syntax error near unexpected token `('
/Users/dev/projects/share-vde-frontend/node_modules/.bin/mock-server: line 1: `const { ApolloServer } = require("apollo-server");'
error Command failed with exit code 2.
My knowledge of writing npm modules is just based on what I've seen in packages I've been using in the past, so maybe I'm missing something key. Do I need some special measures when requiring imports? Or do I need to build and transpile the code? I'm using ES6 syntax, but I feel confident that anyone using this package will be on modern Node.js versions (the package is private and only to be used within our organisation).
Based on the comment from #jonrsharpe above, I solved it by added shabang to the start of the server.js file:
#!/usr/bin/env node
const { ApolloServer } = require("apollo-server");
...

Expect assertions type error -> expect(...).toExist is not a function

I'm testing a NodeJS app. I encountered this error when I ran the tests. The test script is below:
.expect((res) => {
expect(res.headers['x-auth']).toExist();
expect(res.body._id).toExist();
expect(res.body.email).toBe(email);
})
The error showed:
TypeError: expect(...).toExist is not a function
How can I resolve this issue?
The expect assertion library has changed ownership. It was handed over to the Jest team, who in their infinite wisdom, created a new API.
You must now use toBeTruthy()instead of toExist().
You can still install expect as before, npm install expect --save-dev, which is currently at version 21.2.1. Most methods names will remain unchanged except for a few, including toExist().
If you are using Jest you can also use 'toBeDefined()'

using systemjs on node.js (& Angular 2)

Say I have a foo.ts and app.ts as follows:
foo.ts:
export interface Foo {
id: number;
label: string;
};
app.ts:
import {Foo} from './foo'
var myfoo: Foo = { "id": 1, "label": "One" };
console.log(JSON.stringify(myfoo));
After compiling, executing 'node app.js' from the command line runs as expected if I use "module"="commonjs" in my tsconfig.json. Cutting to the chase, what I would like to do is is use my Foo interface client-side with Angular 2, and server-side with node. Inconveniently, the Angular 2 quickstart I am modeling on here wants "module"="system" in tsconfig.json. This configuration causes an error when trying to run 'node app.js':
System.register([], function(exports_1) {
^
ReferenceError: System is not defined`
I have tried following the instructions for using systemjs with node on github, but at this point I am just mashing keys and could use some help. How do I either (a) get my app.ts code running on the server-side using systemjs, or alternately, (b) get the Angular 2 quickstart running with commonjs?
I am going to wrap this up with an answer, even if the question hasn't been up-voted. The solution appears to be to use Gulp to compile the common typescript code (like interface Foo) differently for the client ("module"="system") and the server ("module"="commonjs"). If there is a way to compile the typescript code in the OP with "module"="system" I'd still like to know. But it appears to be kind of academic since everyone manages their project with Gulp or something similar anyway.

Not able to require a node module

I'm new to node js and require js. I installed a node module via npm install(https://www.npmjs.org/package/box-view). The node_modules folder has a box-view/index.js containing:
module.exports = {
BoxView: BoxView,
createClient: function (key) {
return new BoxView(key);
}
};
When I try to access the module using require:
require ['box-view'], () ->
console.log("Ready")
I get:
GET http://127.0.0.1:9000/js/box-view.js 404 (Not Found).
Looks like I'm doing a basic mistake. Thanks in advance!
Node has a simple module loading system - files and modules are in one to one correspondence.
var boxView = require('box-view');
console.log("Ready");
I think problem is because you did a npm install box-view so it will be under node_modules/box_view/index.js.
But using require you are just saying require ['box-view'] so it's looking ./box-view.js
This will work
require(["node_modules/box-view/index"]
but this is not a good practice.
You should have a look on require node manual. It tells how to use requirejs with node.

Resources