简体   繁体   English

使用节点访问根目录

[英]Access Root directory using Node

Is there any way to access the Linux root ('/') directory through node? 有什么方法可以通过节点访问Linux根目录('/')? Right now, I have something like this: 现在,我有这样的事情:

multipart   = require('connect-multiparty')
app.use(multipart({
   uploadDir: config.tmp
}));

...

var file = req.files.file;
fs.renameSync(file.path, ".", function(err) {
    if(err) console.error(err.stack);
})

but the problem is that file.path is refering to a folder inside the Linux root rather than the project's root. 但问题是file.path指向Linux根目录内的文件夹,而不是项目根目录。

The most literal answer to your question 您问题的最真实答案

Is there any way to access the Linux root ('/') directory through node? 有什么方法可以通过节点访问Linux根目录('/')?

Is yes, by using / . 是的,通过使用/ Node.js shouldn't be giving any special treatment to it. Node.js不应对其进行任何特殊处理。 Root is a directory just like any other. 根目录与其他目录一样。

On to your code... 转到您的代码...

fs.renameSync takes a source first and destination second. fs.renameSync获取源,然后再获取目标。 You are renaming a file to . 您正在将文件重命名为. , which represents the current working directory. ,代表当前的工作目录。 I'm not even sure if you can rename something to . 我什至不知道您是否可以将某些内容重命名为. . I would extract the filename from the path, then set the destination to the root directory plus that file name. 我将从路径中提取文件名,然后将目标设置为根目录以及该文件名。

How to access the root directory, which as you said, is / , well, use / . 如何访问根目录,即如你所说,是/ ,那么,使用/

By the way, why are you using renameSync with a callback and nothing after it? 顺便说一句,为什么要在带有回调的情况下使用renameSync ,之后又什么也不做? According to the documentation, this is not valid. 根据文档,这是无效的。 It's either async with a callback, or sync without a callback. 它要么与回调异步,要么与没有回调同步。 So your callback is probably not firing. 因此,您的回调可能不会触发。

var file = req.files.file;
fs.rename(file.path, '/' + path.basename(file.path), function(err) {
    if(err) console.error(err.stack);
});

By the way, I have to advocate strongly against an application writing files to the Linux root directory, for a number of reasons: 顺便说一句,出于多种原因,我必须强烈反对将文件写入Linux根目录的应用程序:

  1. Requires root privileges, which opens a can of worms. 需要root特权,这会打开一罐蠕虫。
  2. Nobody would ever think to look there 没有人会想到那里
  3. The slightest bug could cause irrevocable damage. 丝毫的错误可能会造成无法挽回的损害。 What if the desired file name is "etc" or "boot"? 如果所需的文件名是“ etc”或“ boot”怎么办?
  4. There are a million better locations for storing files uploaded from a web server. 有上百万个更好的位置用于存储从Web服务器上载的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM