nodegit reset/revert single file - javascript

I'm trying to reproduce the checkout file operation using nodegit for reverting current changes of a file.
git checkout -- filename.ext
My first attempt was to use checkoutRef function from Repository object, like this:
nodegit.Repository.open(gitRepo)
.then(function (repo) {
repo.checkoutRef('filename.ext',{
checkoutStrategy: nodegit.Checkout.STRATEGY.FORCE
}).then(function (data) {
console.log(data);
});
});

Try the following code: ;-)
try {
const commit = await repository.getBranchCommit("origin/master");
const tree = await commit.getTree();
const resCheckout = await Checkout.tree(repository, tree, { checkoutStrategy: Checkout.STRATEGY.FORCE, paths: ["YOUR_FILE_PATH"] });
} catch (err) {
console.log(err)
}

I think Reset.default is what you want.

Related

having problems with `fs.writeFile` it doesn't create files

I'm trying to start a script that itself creates a model file in json using fs.writeFile. The problem is when I run the script using node file.js. It is supposed to create a new file face-expression-model.json in directory /models but it doesn't create anything and doesn't show any errors.
I tried to use another library fs-extra not working as well, tried to make the script to create model directory fs.WriteDir not working eitheritried to add process.cwd() to bypass any authorisation when creating the file but didn't work. I also tried to add try/catch block to catch all errors but it doesn't show any errors and it appears that the file was created for the first while but NOPE, unfortunately.
Here is the code I'm using.
const axios = require("axios");
const faceapi = require("face-api.js");
const { FaceExpressions } = faceapi.nets;
const fs = require("fs");
async function trainModel(imageUrls) {
try {
await FaceExpressions.loadFromUri(process.cwd() + "/models");
const imageTensors = [];
for (let i = 0; i < imageUrls.length; i++) {
const response = await axios.get(imageUrls[i], {
responseType: "arraybuffer"
});
const image = new faceapi.Image();
image.constructor.loadFromBytes(new Uint8Array(response.data));
const imageTensor = faceapi.resizeImageToBase64Tensor(image);
imageTensors.push(imageTensor);
}
const model = await faceapi.trainFaceExpressions(imageTensors);
fs.writeFileSync("./models/face-expression-model.json", JSON.stringify(model), (err) => {
if (err) throw err;
console.log("The file has been saved!");
});
} catch (error) {
console.error(error);
}
}
const imageUrls = [
array of images urls here
];
trainModel(imageUrls);
I don't know exactly why but I had the same problem a while ago. Try using the "fs.writeFile" method. It worked for me.
fs.writeFile("models/face-expression-model.json", JSON.stringify(model), {}, (err) => {
if (err) throw err;
console.log("The file has been saved!");
});
Good luck with that!

Downloading and sending pdf document in Node through API

I am new to node, I want to download a pdf document from some another url when person hits a post request in the back-end, change the name of file and send the file back to original client where the pdf will be downloaded.
NOTE the file should not be saved in server
first there is controller file which contains following code
try {
const get_request: any = req.body;
const result = await printLabels(get_request,res);
res.contentType("application/pdf");
res.status(200).send(result);
} catch (error) {
const ret_data: errorResponse = await respondError(
error,"Something Went Wrong.",
);
res.status(200).json(ret_data);
}
Then after this the function printLabels is defined as
export const printLabels = async (request: any,response:any) => {
try {
const item_id = request.item_id;
let doc=await fs.createReadStream(`some url with ${item_id}`);
doc.pipe(fs.createWriteStream("Invoice_" + item_id + "_Labels.pdf"));
return doc;
} catch (error) {
throw error;
}
};
Using above code, I am getting error as no such file found. Also, I don't have access of front end so is it possible to test the API with postman for pdf which I am doing or my approach is incorrect?
Next solution working for Express, but I'm not sure if you're using Express-like framework. If that, please specify which framework you're using.
At first, you need to use sendFile instead of send:
try {
const get_request: any = req.body;
const result = await printLabels(get_request,res);
res.contentType("application/pdf");
res.status(200).sendFile(result);
} catch (error) {
const ret_data: errorResponse = await respondError(
error,"Something Went Wrong.",
);
res.status(200).json(ret_data);
}
Then, you returning readStream, instead of path to file. Notice, you need to use absolute path to do that.
const printLabels = async () => {
try {
let doc= await fs.createReadStream(path.join(__dirname, 'test.pdf'));
doc.pipe(fs.createWriteStream("Invoice_test_Labels.pdf"));
return path.join(__dirname, 'Invoice_test_Labels.pdf');
} catch (error) {
throw error;
}
};
About PostMan, of course you can see it or save it to file:

How to commit and push with simple-git (NODEJS)?

I'm trying to do a simple Commit & Push to an existing repo using simple-git however I can't find
any example regarding this issue in the API in NPM (or Github) of simple-git.
I'm talking about this package : https://www.npmjs.com/package/simple-git
Consider the code :
const gitRepo = 'REPO-URL';
const tempFolder = '...';
// Simple Git
const simpleGit = require('simple-git')();
const options = ['--depth', '1'];
const callback = () => {
console.log('Done cloning!');
// Now change some code in the cloned code
// and commit && push
};
// Cloning ...
simpleGit.outputHandler((command, stdout, stderr) => {
stdout.pipe(process.stdout);
stderr.pipe(process.stderr)
stdout.on('data', (data) => {
// Print data
console.log(data.toString('utf8'));})
})
.clone(gitRepo, tempFolder, options, callback);
How can we commit and push using simple-git ?
Like #Lawrence Cherone said :
You can just use the basic commands as is.
This is how i used it in my project ( though i got a submodule in it where this example is changing its (git)working directory to content(submodule) first. After that i just commit with a message.
app.post("/gitCommit", async function(req, res) {
try {
await git.cwd({ path: 'content' }).commit(req.body.msg);
res.sendStatus(200)
} catch(err) {
console.log(err)
}
});
If you already have a working and initialised repo your in,
then you could just do the following:
await git.commit("your_message")
await git.push()
await git.push('origin', 'master')
You can leave out the 'await' part depending on your code running async.

Adding Data to Event Emitter

I am using "proxy-lists": "^1.16.0" package to obtain proxies.
I would like to save all incoming Array-Objects into my own array to later save it to the db.
When running the below example my array is empty and no file is written:
const ProxyLists = require('proxy-lists');
const fs = require('fs');
global.__basedir = __dirname;
const options = {
countries: null
};
// `gettingProxies` is an event emitter object.
const gettingProxies = ProxyLists.getProxies(options);
const data = []
gettingProxies.on('data', function (proxies) {
console.log(proxies);
data.push(proxies)
});
gettingProxies.on('error', function (error) {
console.error(error);
});
gettingProxies.once('end', function () {
fs.writeFile(__basedir + "data/file.txt", data, function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
});
Any suggestions what I am doing wrong?
I appreciate your replies!
Looks good to me, but when I tested locally, I see that there was an issue concatenating your paths. Try __basedir + "/data/file.txt" (or use path.join)

Saving JSON in Electron

I am building an app using Electron. In this app, I am building a data structure using JSON. My data structure looks like this:
{
items: [
{ id:1, name:'football' },
{ id:2, name:'soccer ball' },
{ id:3, name:'basketball' }
]
}
I want to save this JSON to a file called "data.json". I want to save it to a file because I want to load the next time the application starts. My challenge is, I do not know how to save the data. In fact, I'm not sure where I should even save the file. Do I save it in the same directory as the app? Or is there some cross-platform approach I should use?
Currently, I have the following:
saveClick: function() {
var json = JSON.stringify(this.data);
// assume json matches the JSON provided above.
// Now, I'm not sure how to actually save the file.
}
So, how / where do I save JSON to the local file system for use at a later time?
Electron lacks an easy way to persist and read user settings for your application. electron-json-storage implements an API somehow similar to localStorage to write and read JSON objects to/from the operating system application data directory, as defined by app.getPath('userData').
Electron uses node.js as its core. You can use the following:
var fs = require("fs");
read_file = function(path){
return fs.readFileSync(path, 'utf8');
}
write_file = function(path, output){
fs.writeFileSync(path, output);
}
For write_file(), you can either pass "document.txt" as the path and it will write it to the same directory the html file it was run from. You can also put in a full path like "C:/Users/usern/document.txt" and it will write to the specific location you want.
Also, you can choose any file extention you want, (ie. ".txt", ".js", ".json", etc.). You can even make up your own!
I wrote a simple library that you can use, with a simple interface, it also creates subdirectories and works with promises/callbacks.
it will save the data into app.getPath("appData") as the root folder.
https://github.com/ran-y/electron-storage
Installation
$ npm install --save electron-storage
usage
const storage = require('electron-storage');
API
storage.get(filePath, (err, data) => {
if (err) {
console.error(err)
} else {
console.log(data);
}
});
storage.get(filePath)
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});
storage.set(filePath, data, (err) => {
if (err) {
console.error(err)
}
});
storage.set(filePath, data)
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});
`const fs = require('fs');
let student = {
name: 'Mike',
age: 23,
gender: 'Male',
department: 'English',
car: 'Honda'
};
let data = JSON.stringify(student, null, 2);
fs.writeFile('student-3.json', data, (err) => {
if (err) throw err;
console.log('Data written to file');
});
console.log('This is after the write call');`
There are multiple steps:
Step 1: As of version 5, the default for nodeIntegration changed from true to false. You can enable it when creating the Browser Window:
const createWindow = () => {
const win = new BrowserWindow({
width: 1000,
height: 800,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
})
}
Step 2:
function writetofile() {
let configsettings = {
break: output.innerHTML,
alwaysonoff: toggleoutput.innerHTML,
};
let settings_data = JSON.stringify(configsettings, null, 2);
const fs = require("fs");
fs.writeFileSync("assets/configs/settings.json", settings_data);
}

Categories

Resources