admin管理员组

文章数量:1293605

I want to create a function that removes a file from the server. I intend to use this function to restore settings (i.e. db files) to their default state. I run my server using the following mand:

node server.js

I am aware of node.js's File System but I don't know how to use it on the browser side. I did some light reading on the issue and it seems to me that this kind of interaction is not possible due to security reasons. How do I go about this?

I want to create a function that removes a file from the server. I intend to use this function to restore settings (i.e. db files) to their default state. I run my server using the following mand:

node server.js

I am aware of node.js's File System but I don't know how to use it on the browser side. I did some light reading on the issue and it seems to me that this kind of interaction is not possible due to security reasons. How do I go about this?

Share Improve this question asked Apr 21, 2015 at 3:17 DennisDennis 3091 gold badge6 silver badges18 bronze badges 3
  • 3 Why do not you create an API on node.js side and call that API from browser to get your work done? – Jayram Commented Apr 21, 2015 at 3:20
  • extention to @Jayram, expose an endpoint like deleteFile and on that request delete the file, you shouldn't be doing this on client side, it must be on server side. – Mritunjay Commented Apr 21, 2015 at 3:22
  • 2 Node.js is a server. The browser uses get or post mands to municate with the server. To carry out an action you design a route in the server that does what you want and you send that URL to the server from the browser and pass any data you need. The server receives that specific URL, parses out from the URL what the client is asking to be done and carries out the action. – jfriend00 Commented Apr 21, 2015 at 3:38
Add a ment  | 

3 Answers 3

Reset to default 8

You cannot use Node's fs in the browser and have it directly affect the file system on the server. fs is for use on locally available file systems only. You will need to create an API or use some other technique.

As other answers are saying, calling node server's method directly from client side is not possible, however indirectly you can do it by sending a request from the browser. On Node.JS part you can create an http server, client would call it, then server may perform an action.

However you should keep in mind, that removing files this way may be dangerous and you need to make sure on the server side, that you allow to remove only what you really want to be removed. For example you may allow to delete files only from specific directories (not just any file!).

There are really multiple ways to do it. Either you can do it in pure node (http.Server class), or you can use some extra modules e.g. express (which helps you to create an http server with just few lines of code) or jxm (which helps you to create client-server messaging system - also with few lines of code).

Since I'm familiar with jxm, I've made a simple example for you:

server.js

var server = require('jxm');
var fs = require("fs");

server.setApplication("Hello World", "/", "STANDARD-KEY");
server.linkResource("/", ["./index.html", "text/html"]);

server.addJSMethod("removeFile", function (env, param) {;
  if (fs.existsSync(param)) {
    fs.unlinkSync(param);
    server.sendCallBack(env, "File Deleted: " + param);
  } else {
    server.sendCallBack(env, "File does not exist: " + param);
  }
});

server.start();

index.html

<!DOCTYPE html>
<html>
<head>
    <script src="/jx?ms=connect" type="text/javascript"></script>
</head>
<input type="button" id="btnRemove" value="Remove temp.txt file" disabled="disabled"/>
<script type="text/javascript">

    document.onjxready = function () {
        jxcore.Start(function (status) {
            var btn = document.getElementById('btnRemove');
            btn.disabled = "";
            btn.onclick = function () {
                jxcore.Call("removeFile", "temp.txt", function (ret) {
                    alert(ret);
                });
            };
        });
    };
</script>
</body>
</html>

Below is how you can run it. Just once you need to install jxm module:

$ npm install jxm

Now you can start the server:

$ node server.js

After that you can go to the browser (http://localhost:8000/) and click the button.

Even though jxm works best with JXcore (they both e from the same team), it works with Node.JS as well (as the above example shows).

Thanks for all the answers and ments. They've been helpful in pointing me to the right direction. What I actually wanted was to make a simple API call from the client. Here's what I did using express:

var app = express();
var settingsapirouter = require('./../../settings/settingsapi');
app.use('/api/settings', settingsapirouter);

In settingsapi, I define:

module.exports = function (...) 
{
    var router = express.Router();

    router.route('/restoredb')
        .post(function (request, response) {
              ...
              });
}

In the client's JS:

function restoreSettings()
{
    $.ajax({
        url: '/api/settings/restoredb',
        type: 'POST',
    })
    .done(function() {
        console.log("success");
    }); 
}

本文标签: javascriptUsing nodejs39s File System functions from a browserStack Overflow