Node script use folder name as parameter [closed] - node.js

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I want to execute a command for each directory in my packages directory. In the command I want to use part of the directory name.
packages
folder-one
folder-two
folder-three
So for each folder execute command 'one' etc
Does anyone have some pointers for this?

Using fs.readdir to list directory contents and child_process.exec to run the command:
const { readdir } = require('fs/promises');
const { exec } = require('child_process');
readdir(__dirname + '/packages').then(packages => {
for (let packageName of packages) {
packageName = packageName.replace(/^folder-/, ''); // remove the 'folder-' part
exec(`your_command_here '${__dirname}/packages/${packageName}'`, (err, stdout, stderr) => {
if (err) {
console.log(err);
}
// if needed you can read the process' stdout and stderr
});
}
});

Related

How to use fs.writeFileSync to write a fetched JS file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 days ago.
Improve this question
I'm fetching a JS file over the network.
ie:
// file is a JS file
// for example: console.log("I am file")
const file = await get('/api/file/1')
I'm not sure how to feed this type of data to fs. I think it needs to be a Buffer but I haven't gotten it to work:
const dataAsBuffer = Buffer.from(file, 'utf-8')
Then I try:
fs.writeFileSync(filePath), dataAsBuffer, (err) => { ...
But get: TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
How can I write a JS file I fetched, to local directory?
EDIT:
the output of get:
// initialize code called once per entity
Test.prototype.initialize = function() {
};
// update code called every frame
Test.prototype.update = function(dt) {
};
console.log('hell oworld');
Fixed: No callback in writeFileSync

Create and manage AWS instances via node.js [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
I'm try create AWS instance with Node.js api that will manage other instances and install the docker image but I can't find any docs or tutorials
To use the AWS SDK
First of all you should npm install aws-sdk.
It's a bit confusing, instance definitions are actually called "reservations". And creating one of them is called "runInstance".
So, of course you first need to initialize your EC2 object.
import { EC2, config } from 'aws-sdk';
config.loadFromPath(__dirname + "/../aws.config.json");
const ec2: EC2 = new EC2(); // to start/stop instances
Next, I personally try to use promises whenever I can when I work with the AWS instances. They clean up the code considerably.
import { promisify } from 'util';
If you already have a reservation, you can start it using its instance id.
const params: EC2.StartInstancesRequest = { InstanceIds: [instanceId] };
const result: EC2.StartInstancesResult = await promisify((cb) => ec2.startInstances(params, cb))();
And you can also stop it like that:
const params: EC2.StopInstancesRequest = { InstanceIds: [instanceId] };
const result: EC2.StopInstancesResult = await promisify((cb) => ec2.stopInstances(params, cb))();
To create your instance you need this:
const params: EC2.RunInstancesRequest = { InstanceType: "t1.micro", ImageId: "ami-31814f58", MinCount: 1, MaxCount: 1 };
const result: EC2.Reservation = await promisify((cb) => ec2.runInstances(params, cb))();
And finally, to list your instances/reservations (with some optional filters):
const stateFilter = { Name: "instance-state-name", Values: ["running"] };
const idFilter = { Name: "instance-id", Values: [instanceId] };
const params: DescribeInstancesRequest = { Filters: [stateFilter, idFilter] };
const result: EC2.DescribeInstancesResponse = await promisify((cb) => ec2.describeInstances(params, cb))();
The response contains a collection of reservations, and for each reservation a collection of instances.
Your own images
To use your own images, you should create an "Amazon Machine Image" (AMI) in advance.
You may want to set up an "Elastic Container Registry" (ECR). You can push a docker image to this repository: https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html

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 extract a single file from a large ZIP archive [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How to extract one file from zipped directory?
Zlib doesn't have any file browsing features, neither does extract-zip
So I don't know what to use.
You can use EvanOxfeld/node-unzip parse zip file contents:
var fs = require('fs')
var unzip = require('unzip')
var path = require('path')
var mkdir = require('mkdirp')
fs.createReadStream('./archive.zip')
.pipe(unzip.Parse())
.on('entry', function (entry) {
var fileName = entry.path
var type = entry.type
if (type==='File' && fileName === 'dir/fileInsideDir.txt') {
var fullPath = __dirname + '/output/' + path.dirname( fileName )
fileName = path.basename( fileName )
mkdir.sync(fullPath)
entry.pipe(fs.createWriteStream( fullPath + '/' + fileName ))
} else {
entry.autodrain()
}
})
[ Example archive ]

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