0

Consider the below code:

// upload.js
var fs = require('fs')
var newPath = "E:\\newPath";
var oldPath = "D:\\oldPath";

exports.uploadFile = function (req, res) {
fs.readFile(oldPath, function(err, data) {
    fs.writeFile(newPath, data, function(err) {
        fs.unlink(oldPath, function(){
            if(err) throw err;
            res.send("File uploaded to: " + newPath);
        });
    });
});
};

// app.js
var express = require('express'), // fetch express js library
upload = require('./upload'); // fetch upload.js you have just written

var app = express();
app.get('/upload', upload.uploadFile); 

app.listen(3000);

In the above code, I need to assign the new path dynamically by passing two parameters as query string such as

1. Drive and 2. Folder name.

How to give the query string in code file and how to run the program to achieve the GET request?

1 Answer 1

2

You can access query-string parameters via req.query. Also, you could probably just use fs.rename instead of manually reading, writing, and unlinking a file.

Sign up to request clarification or add additional context in comments.

3 Comments

Could you please come up with a simple example?
req.query.drive and req.query.folder? For fs.rename it's just something like fs.rename(oldPath, newPath, function(err) { if (err) throw err; res.send('Rename successful'); });
Also, you generally shouldn't use a GET request that changes things on the server. That should be reserved for other HTTP verbs, like POST. So you would use app.post('/upload', upload.uploadFile); and the client would POST to /upload?drive=E&folder=newPath. Then just assemble those two parameters to make a valid path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.