How to Properly Import a Module Into A File (Node.js) - node.js

I am trying to make a video chat using WebRTC and Node.js. I currently am trying to add a selectable microphone (e.g. being able to change mics and webcams). I made the function, but when I try to import a function from the file that generates the IDs of the the devices, it doesnt work. Note that I am not currently getting any errors, instead, when I add the import statement to the file, nothing shows up (except for the dropdowns that change the mic and webcam).
Is there a reason that node wont let me import a function?
Note that the file that I am trying to import into exports a bunch of functions (thats the purpose of it), RTC.js. However, I also tried importing into another file and it didnt work either (the file that imports the first file, rtc.js).
Thanks in advance
The github repository is located here

Export is like this line you already did https://github.com/divinelemon/VideoChatAppSwitchMics/blob/master/ws/stream.js#L34
module.exports = stream;
Import is like here you did https://github.com/divinelemon/VideoChatAppSwitchMics/blob/master/app.js#L5
let stream = require( './ws/stream' );

you can also ES6 import/export function:-
const someFunction = (){
...
}
export default someFuntion ( in the case on single function)
When you want to export multiple functions
export { someFunction1, someFunction2}.
Now the place where you want to import
import somFunction from 'filelocation' ( note in case of default exports you need to use the same name of the function)
In the case of multiple functions.You can change the function name but keep in mind the order of exports and imports.
import { myFunction1,myFunction2} from 'fileLocation'

Related

Node.js package script that runs every time a file is changed

I'm developing a node.js package that generates some boilerplate code for me.
I was able to create this package and if I run every module individual it works fine and generates the code as expected.
My idea now is to import this package in another project and have it generate the code.
I have no idea to how to achieve this or even if it's possible.
The perfect solution would be that every time a file changed in a set of folders it would run the package and generate the files but if this isn't possible it would be ok as well to expose or command to manually generate this files.
I have created a script to run the generator script but it only works on the package itself and not when I import it in another project.
Thanks
I think you want the fs.watch() function. It invokes a callback when a file (or directory) changes.
import { watch } from 'fs';
function watchHandler (eventType, filename) {
console.log(`event type is: ${eventType}`) /* 'change' or 'rename' */
if (filename) {
console.log(`filename provided: ${filename}`)
} else {
console.log('filename not provided');
}
}
const options = { persistent: true }
const watcher = fs.watch('the/path/you/want', options, watchHandler)
...
watcher.close()
You can use this from within your nodejs app to invoke watchHandler() for each file involved in your code generation problem.

Runtime import in typescript

I want to import a json file at the runtime.
My code:
const path = "../../assets/data/"+<fileprefix>+".json"
const data : Information = await import(path);
fileprefix here changes at the runtime.
I'm getting module not found error as below.
Error: Cannot find module '../../assets/data/US.json
US here is the fileprefix that comes at runtime.
Is there any way I can make node to find the module at the runtime?
It's a little unclear what you mean by import. If you are referring to the ES6 import (import something from 'something'), then, no. You can't do that. However, I see that you're doing import(path). Is import() a library of some sort or are you expecting that to work with an es6 import?
Here's what you should do (IMO):
What you can do, is serve your json files as static files and then use the fetch api to bring that json in.
Ex:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
Obviously, instead of the url being https://jsonplaceholder.typicode.com/todos/1, it would the url to your static json file.
One other option would be to get all of your json files (or references to your json files) into a single module. Then you can import that module and then call whatever method you need to call so that the correct json file comes back. Here's an article on how to go about this: https://medium.com/#leonardobrunolima/javascript-tips-dynamically-importing-es-modules-with-import-f0093dbba8e1

How to eval es6 code from NodeJS at runtime with Babel?

I'm trying to build a nodeJS tool to help me analyzing another AngularJS source code.
The idea is to :
read some of the angular project javascript files
for each file, grab the content
eval the content from the file
do some stuff
The problem I'm facing is that my Angular source code uses es6 features like import, export, arrow functions, ...Etc. and I using nodeJS which does not support these features yet.
So I tried to use #babel/core transform() from my Node app code, but it doesn't work. I keep getting error like Unexpected identifier which means it doesn't understand the import {stuff} from 'here'; syntaxe.
srcFiles.forEach(content => {
try {
(function() {
eval(require("#babel/core").transform(content.text).code)
}.call(window, angular));
} catch (e) {
console.log(e);
}
});
An sample test file :
import _ from 'loadash';
console.log("I'm a file with import and export");
export const = 42;
Any idea how I can get this stuff working ? Or maybe another approach ?
You can pass options as the second parameter of transform method. See examples here

Setting up a central logging package for multiple applications

Say we create a package called 'my-loggers' that can be reused, that looks like this:
import bunyan = require('bunyan');
const loggers = {};
export const getLogger = function(name, config){
if(loggers[name]){
return loggers[name];
}
return loggers[name] = bunyan.createLogger(config);
};
then in each application, we do:
npm install -S my-loggers
then we use the logger like this:
import * as MyLoggers from 'my-loggers';
import config = require('../my-app-config');
const log = MyLoggers.getLogger('my-app', config.logging);
the problem is it really requires 3 lines of code to retrieve the logger for each file in each app.
I am trying to figure out a way to create a single package that can retrieve a logger for any file in any app, and I am trying to
cut everything down to just one LoC.
I am also trying to avoid relative paths.
I cannot think of a solution that involves 1 logging package for all our apps. The only thing I can think of is either a separate logging package per app (which is kinda lame), or doing a trick where we symlink some code from our project into node_modules, upon npm install, which allows us to avoid relative paths.
Anyone know of a good way to solve this one?
Ok, I have a solution. We can just do this:
import log from 'my-loggers/app1'
import log from 'my-loggers/app2'
import log from 'my-loggers/app3'
that way we can store different loggers in the same package.

Express4: Storing db instance

In express4, is it bad practice to store the db instance in app.locals or store it using app.set? Because I was thinking about it, since I will need it throughout my app it will be easier to access.
It should work just fine and no, I don't think it's bad practice (at least not horrible) - after all, app.locals is intended to provide you a safe place to put your global values.
However, using Express to store miscellaneous global values like this does result in your application being tightly bound to Express. If you ever decide that you want to remove Express and replace it with something else, you're going to have to hunt down and change all those references to app.local that are now scattered throughout your code.
If you want to avoid this, one simple pattern is to create a module exporting the value you want - this allows you to keep all the associated code in one place and import it whenever you need it. For example:
// modules/database.js
// initialize the database
const db = initializeDatabase();
// export a "getter" for the database instance
export const get = () => db;
Then, when you want to use the database instance:
// index.js
// import the database "getter"
import { get } from './modules/database';
// perform a query
const rows = get().query('SELECT * FROM table');
Just import modules/database anywhere you want to use the database.

Resources