Nodejs Code Reusing Best Practices - node.js

I am new to nodejs. I can't get my mind over organizing module code reusing in Nodejs. For example :
Let's say I have 3 files, which corresponds to 3 library files I wish to load. Then, I have 5 files which requires the 3 libraries.
Will I have to repeat typing the following in the 5 files?
require("./library-1.js");
require("./library-2.js");
require("./library-3.js");
Is there any way for me to automatically include these 3 lines of code (which is potentially more than just 3) in the 5 files?

Generally yes you end up with this kind of repetition, but the explicit dependencies are really helpful next year when you go to refactor your app. However, You can very easily wrap all 3 libraries into a monolithic module if you prefer:
//monolith.js
exports.lib1 = require('./library-1');
exports.lib2 = require('./library-2');
exports.lib3 = require('./library-3');
Then just load that with var monolith = require('./monolith');

Yes, you can require a folder as a module. If you want to require() a folder called ./test/.
Inside ./test/, create a package.json file with the name of the folder and a main javascript file with the same name, inside a ./lib/ directory.
{
"name" : "test",
"main" : "./lib/test.js"
}
Now you can use require('./test') to load ./test/lib/test.js.
similarly you can require other files

Related

How to create same path to directory on different platforms in Python?

In the piece of code I have, there are many instances where I have the following line
'/home/myname/directory'
For example, I have the following lines of code
filepath = os.listdir('/home/myname/directory')
for content in filepath
# do something
In the next part of the project, I have to share the code with some one else. I know this person runs openSUSE. If I want code to create that specific directory with the same path to the directory as mine, what do I need to include?
I know its going to involve the OS module but i am not sure which functions and methods to use.
Your code can check the existence of the directory and create it if not found:
if not os.path.exists("/home/myname/directory"):
os.makedirs("/home/myname/directory")
# do something

How to include static files on Serverless Framework?

I'm creating a NodeJS service with serverless framework to validate a feed so I added a schema file (.json) to the service but I can’t make it work.
It seems to not be included in the package. Lambda doesn't find that file.
First I just run sls package and check the zip contents but the file is not present.
I also tried to include the file with:
package:
include:
- libs/schemas/schema.json
but still not works.
How can I make sure a static file is included in the package and can be read inside the lambda function?
It depends on how you are actually trying to load the file.
Are you loading it with fs.readFile or fs.readFileSync?
In that case, Serverless doesn't know that you're going to need it. If you add a hint for Serverless to include that file in the bundle then make sure that you know where it is relative to your current working directory or your __dirname.
Are you loading it with require()? (Do you know that you can use require() to load JSON files?) In that case, Serverless should know that you need it, but you still need to make sure that you got the path right.
If all else fails then you can always use a dirty hack.
For example if you have a file 'x.json' that contains:
{
"a": 1,
"b": 2
}
then you can change it to an x.js file that contains:
module.exports = {
"a": 1,
"b": 2
};
that you can load just like any other .js file, but it's a hack.
From what I've found you can do this in many ways:
As it is stated in another answer: if you are using webpack you need to use a webpack plugin to include files in the lambda zip file
If you are not using webpack, you can use serverless package commnad (include/exclude).
You can create a layer and reference it from the lambda (the file will be in /opt/<layer_name>. Take in consideration that as today (Nov20) I haven't found a way of doing this if you are using serverless.ts without publishing the layer first (lambda's layer property is an ARN string and requires the layer version).
If your worried about security you can use AWS Secrets as it is stated in this answer.
You can do what #rsp says and include it in your code.
For those struggling to find a solution in 2022: use package.patterns parameter. Example:
package:
patterns:
- libs/schemas/schema.json
- !libs/schemas/schema-prod.json
(! in front of the file path excludes specified pattern)
Documentation: https://www.serverless.com/framework/docs/providers/aws/guide/packaging

How to copy files as templates, injecting values to them, to a different folder?

I used this library, mem-fs-editor (https://github.com/sboudrias/mem-fs-editor), in a Yeoman generator a few weeks ago. It worked nicely, but now I tried to use it again in a different scope and I couldn't do anything. Obs: I used it because this is the library Yeoman provides to handle the file system.
In Yeoman Generators we can copy files from a template folder, passing values to inject in the code, to a different folder. And that's precisely what I need, but I can't use Yeoman this time.
I tried the same code I used in my Yo Generator, but it don't work. So I'm not sure how mem-fs works. No errors are thrown and even the code provided by the author of the project don't work to me.
I tried this (and some other things with copyTpl) with no success
var memFs = require('mem-fs');
var editor = require('mem-fs-editor');
var store = memFs.create();
var fs = editor.create(store);
console.log(fs.write('./somefile.js', 'var a = 1;'));
Anyone knows how it works or what else I can do to make this happen?
mem-fs-editor author here.
mem-fs stands for memory file-system. All the files you creates are stored in memory and won't get written to disk until you call:
editor.commit(callback);
Yeoman does that automatically for you. It is this way with Yeoman to collide every file changes together and then being able to only prompt for file conflicts once (rather than everytime a single file is being written to).

Default path for file import Julia

I have created a package and am now creating my tests within the package. For one test my inputs are a set of files and my outputs will be a different set a files created within the test.
I am saving the input files in the test directory of my package and would like to save the output files there too. Since others may run this test, I do not want to specify the input/output file location using my own path eg /home/myname/.julia/v4.0/MyPackage/test/MyInputFile.txt
How do I specify that the input location is within the package's test folder?
So basically how do I tell Julia to look in the packages's folder under the test directory and not have to worry about specifying the entire path including user name etc?
For example currently I have to say
readtable(/home/myname/.julia/v4.0/MyPackage/test/MyInputFile.txt, separator = '\t', header = false)
But I'd like to just be able to say
readtable(/MyPackage/test/MyInputFile.txt, separator = '\t', header = false)
so that no matter who the user of the package is and where they may store the package, they can still run the test?
I know that LOAD_PATH gives the path Julia looks for packages but I can't find any information on where it looks when importing files.
joinpath(Pkg.dir("MyPackage"), "test") is what you need.
As #GnimucK mentioned in a comment, a better solution is
dirname(#__FILE__)
Why is this better? A package could be installed and used from somewhere else (not the standard package directory). Pkg.dir is "stupid" and does not know better. This is rare, of course, and in most cases it won't matter.

node.js express - require file in all files

Let say I need to do
require('./config/globals.js');
in many files, what is the best way to do it? Writing this line in every file or there is some more elegant way?
Searching "node.js how to require in many files" returns answers to "node.js require all files in a folder" :(
If you have some global variables for your application that consists of multiple files and you want them to be accessible via all of the files in your application, define them as global variables in your main .js file:
server.js
global.myName = 'Carl';
require('app1.js');
require('app2.js');
In that scenario, both app1.js and app2.js will be able to read and write to the variabme myName.
Change the variables defined in your globals.js to follow the structure above, and it should achieve your goals - assuming I understood the question correctly.
EDIT: As seanhodges suggested, you could also keep the globals.js and edit accordingly:
Server.js
require('globals.js)
require('app1.js');
require('app2.js');
globals.js
global.myName = 'Carl';

Resources