-1

I'm new to Node and am trying to build a simple server in Node using Express. The requests are in the form of say /input00001/1/output00001. What I need to do is to parse this request and if the flag is 1 (middle value), I need to replace the file \home\inputfiles\input00001.txt with file \home\outputfiles\output00001.txt. How is it possible to do that?

Here is my simple server so far. I'm OK with not using the Express and pure NodeJs if that makes things easier.

const express = require('express');
const app = express();
const port = 8000;

app.get('/', (request, response) => {
  response.send('Hello from Express!');
  request.param
});

app.get('/*', (request, response) => {
  response.send('Start!');
    var url = request.originalUrl;
});

app.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err);
  }
  console.log(`server is listening on ${port} for incoming messages`);
});

1 Answer 1

0

You should set up a route that expects these items as url parameters and then use those parameters to do what you want. For example if you're url is /input00001/1/output00001 then you could set up a route like this:

app.get('/:input/:flag/:output', (req, res) => {
    var params = req.params
    var input = params.input   //input0001
    var flag = params.flag     // 1
    var output = params.output //output0001

    // now do what you need to with input, flag, and output
    if(typeof flag!=='undefined' && flag==1){
       var file_name_string = '\home\inputfiles\input00001.txt';
       var res = file_name_string.replace("input", "output");    
     }

    console.log(input, flag, output)
    res.send("done")
})
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! so using the : specifies a variable, right? :input means put that string in the variable input?
Yes :input is a route parameter and it will be available on the params object. Lots more here: expressjs.com/en/guide/routing.html under the express route parameters heading.
Thanks. Can you also help with the file copy feature? So I will mark your answer.
@Ariana I think you should add a separate question about that. It's potentially dangerous to accept url information and use it to access the file system. For example you need to handle situation like /..%2F..%2FFoo/1/1000 which would translate to a filename ../../Foo that you might not intend to overwrite. You'll need to sanitize the input, and I'm not sure the best way to do that safely.
Safety is not important for me at this point. But OK, let me post a separate question.

Your Answer

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