Require all files from directory [duplicate] - node.js

This question already has answers here:
node.js require all files in a folder?
(15 answers)
Closed 9 years ago.
Help me please.
I want require all files from directory ?
How best to do it?
I read about require_paths but it does not perform those functions.

You can walk through a directory and require each one:
var mods = {};
var files = fs.readdirSync('your_directory').filter(function(x) { return x.substr(-3) == ".js"; });
for(var i = 0; i != files.length;++i) {
mods[files[i]] = require(path.join('your_directory',files[i]));
}

Related

How to write console logs into a json file [duplicate]

This question already has answers here:
Configure Node.js to log to a file instead of the console
(28 answers)
Closed 6 months ago.
i want to write console logs into logs.json file and saves it like:
{
"1":"consolelog1",
"2":"consolelog2",
"3":"consolelog3"
}
Using node.js, you can use fs:
const fs = require('fs');
function log_to_file(mystuff){
// GET file
const file = JSON.parse(fs.readFileSync('./logs.json'));
// Find number of console.logs already there
let lognumb = -1, cont = true;
while(cont){
if(!(file[lognumb+1]===undefined)){
lognumb++;
continue
};
cont=false
};
file[lognumb+1] = "consolelog"+mystuff;
fs.writeFileSync("./logs.json",JSON.stringify(file));
}
Then, you can use log_to_file("your_console_log_data") to save your data.
Make Sure You Are Using NODE.JS, Not JAVASCRIPT

How to use environment variable in Typescript properly? [duplicate]

This question already has answers here:
using process.env in TypeScript
(19 answers)
Closed 1 year ago.
I'm trying to make a simple api using typescript and when I use any env variable I get an error from TS compiler Tells me that this could be undefined
example
// Not Working
const db = process.env.DB_URL // This gives an error that the result could be a string or undefined
to fix this
I have to make a type guard and check with if statement as follows
const db = process.env.DB_URL
if (db){
// ....
}
Is there a better approach to to such a thing instead of explicitly check for every variable ?
You can apply null check and keep it as string instead of defining two types:
const db: string = process.env.DB_URL ?? ''
// empty strings are falsy/falsey
if (db) { // do this}
else { //do this}

How do you access the directory that your module is in? [duplicate]

This question already has answers here:
How do I get the path to the current script with Node.js?
(15 answers)
Closed 3 years ago.
If you have a module that's being imported in some code, let's say...
var my_cool_module = require('my_directory/my_cool_module');
my_cool_module.print_directory_name();
And I'm in that module's context, say this is the file my_cool_module.js...
function get_dir_name() {
// get the directory name...
return directory_name;
}
exports.module.print_directory_name = function() {
console.log("This module is in directory " + get_dir_name());
};
How can I get the directory that the module is in (i.e. "my_directory")
I found out from the node.js documentation here that you can use __dirname
function get_directory_name() {
return __dirname;
}

How to use removeAtIndex if var parameter is deprecated [duplicate]

This question already has answers here:
'var' parameters are deprecated and will be removed in Swift 3
(8 answers)
Closed 6 years ago.
I am using a var for IPAddress, for which i wanted to remove trailing slash (/). Now i see a warning that 'var' is deprecated. In such case how can i use removeAtIndex method in new style?
if ipAddress.characters.last == "/" {
ipAddress.removeAtIndex(ipAddress.endIndex.predecessor())
}
Remove var from the function parameter declaration and then create a mutable copy:
func myFunc(ipAddress: String) { // remove the var if you write here var ipAddress
var ipAddress = ipAddress
// change ipAddress here
}
var is only deprecated in function arguments.
See here the original change request:
https://github.com/apple/swift-evolution/blob/master/proposals/0003-remove-var-parameters.md

web-server.js with apache-like DirectoryIndex behavior [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I am using the web-server.js node script to run a webserver on my local machine.
The behavior of web-server.js is to dump a complete file listing if a directory is requested.
instead I would like to emulate the apache DirectoryIndex where by if there is an index.html in the directory it will be served instead.
var fs = require('fs');
http://nodejs.org/api/fs.html You can check for files with this.
I could not find the answer so here is my code that does it.
first I had to change the handleRequest function
if (stat.isDirectory()) {
var indexFile = self.getDirectoryIndex_(path);
if (indexFile)
return self.sendFile_(req, res, indexFile);
return self.sendDirectory_(req, res, path);
}
and here is my implementation to getDirectoryIndex_
StaticServlet.prototype.getDirectoryIndex_ = function(path) {
var result = null;
var files = fs.readdirSync(path);
files.forEach(function(fileName, index) {
if (fileName.match(/^index\./gi)) {
result = path + fileName;
return false; //break foreach loop
}
});
return result;
};

Resources