Требуется Node JS основных модулей из подкаталогов (в NW JS) - PullRequest
0 голосов
/ 13 июля 2020

Я совершенно не понимаю, как использовать базовый модуль Node JS в подкаталогах папки root.
У меня есть приложение со страницей в подкаталоге, где мне нужно чтобы потребовать модуль файловой системы Node JS. Модуль файловой системы (fs) не найден в папке node_modules в каталоге root и, следовательно, у меня много проблем с его работой. (Страница и сценарий, требующие модуля 'fs', работают нормально, когда помещены в каталог root, но не иначе.)


Я также пробовал добавить: "homepage": "./", в пакет. json который, казалось, работал изначально, но после смены каталогов он перестал работать.

Похоже, он также не работает в файлах, отличных от основного файла в документе root.

Это мой пакет. json

{
  "name": "ax-net",
  "version": "1.0.0",
  "description": "",
  "main": "index-main.html",
  "scripts": {
    "start": "nw .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "nw": "^0.46.4-sdk"
  },
  "dependencies": {
    "fs": "0.0.1-security"
  }
}

Index-main. html перенаправляет на другой файл с именем index. html через window.open('index.html');

Это head моего индекса. html, который загружает сценарий norm.js, содержащий require:

<head>
    <title>
        cs | xx xx 2020
    </title>
    <link rel="icon" href="/home/aakash/ax-net/x/samples/icons/ax.png">
    <link rel="stylesheet" type="text/css" media="screen" href="file:///home/aakash/ax-net/x/samples/css/v2/cs.css" />
    <script src="norm.js"></script>
</head>

Это мой norm.js:

const fs = require('fs')
function histforward() {
        history.go(+1);
        //alert("done");
}
function histbackward() {
        history.go(-1);
        //alert("done");
}
function reload() { 
        //Refresh the current page.
        window.location.reload(false); //False for soft refresh
        //alert("done");
}
function edit() {
    let exec = require('child_process').exec;
    var location = process.cwd() + "/" + (document.URL).replace(/^.*[\\\/]/, '');
    exec("code "+ location);
}
function directory() {
    var location = process.cwd();
    window.location.href=location;
}
function read(file, id) {
    fs.readFile(file, (err, data) => { 
    if (err) throw err; 
    document.getElementById(id).innerHTML=data.toString();
    //alert(data.toString()); 
    })
}

Мои инструменты разработчика Журнал консоли окна NW JS: console log

Currently all of these are in the root directory, but still fs only seems to work when the page requiring it (index.html) is set as the main page of the app. It doesn't work when the page is redirected to from another page.

From the searches that I performed, I thought it has got something to do with the document root and the "homepage": "", entry in package.json.


UPDATE-1

I found a partial solution to my problem here :

https://github.com/nwjs/nw.js/issues/3359

, а здесь:

Node-Webkit's (nw js) node-remote Использование

Итак, я добавил следующее в свой package.json:

"homepage": "./",
"node-remote": "*://*",

Теперь страница index.html в каталоге root кажется работать нормально (при перенаправлении на, с главной страницы приложения), но тот же index.html, закопанный в подкаталог, дает следующие ошибки в журналах консоли: enter image description here


UPDATE-2

NOTE: (For clarification) I am running my app using the command npm start, I am using NW JS to run it which like electron uses NodeJS.

NOTE-2 (for the query by Ahmed): running const fs = require('fs'); console.log(fs); through node in terminal gives the following output:

{
  appendFile: [Function: appendFile],
  appendFileSync: [Function: appendFileSync],
  access: [Function: access],
  accessSync: [Function: accessSync],
  chown: [Function: chown],
  chownSync: [Function: chownSync],
  chmod: [Function: chmod],
  chmodSync: [Function: chmodSync],
  close: [Function: close],
  closeSync: [Function: closeSync],
  copyFile: [Function: copyFile],
  copyFileSync: [Function: copyFileSync],
  createReadStream: [Function: createReadStream],
  createWriteStream: [Function: createWriteStream],
  exists: [Function: exists],
  existsSync: [Function: existsSync],
  fchown: [Function: fchown],
  fchownSync: [Function: fchownSync],
  fchmod: [Function: fchmod],
  fchmodSync: [Function: fchmodSync],
  fdatasync: [Function: fdatasync],
  fdatasyncSync: [Function: fdatasyncSync],
  fstat: [Function: fstat],
  fstatSync: [Function: fstatSync],
  fsync: [Function: fsync],
  fsyncSync: [Function: fsyncSync],
  ftruncate: [Function: ftruncate],
  ftruncateSync: [Function: ftruncateSync],
  futimes: [Function: futimes],
  futimesSync: [Function: futimesSync],
  lchown: [Function: lchown],
  lchownSync: [Function: lchownSync],
  lchmod: undefined,
  lchmodSync: undefined,
  link: [Function: link],
  linkSync: [Function: linkSync],
  lstat: [Function: lstat],
  lstatSync: [Function: lstatSync],
  mkdir: [Function: mkdir],
  mkdirSync: [Function: mkdirSync],
  mkdtemp: [Function: mkdtemp],
  mkdtempSync: [Function: mkdtempSync],
  open: [Function: open],
  openSync: [Function: openSync],
  opendir: [Function: opendir],
  opendirSync: [Function: opendirSync],
  readdir: [Function: readdir],
  readdirSync: [Function: readdirSync],
  read: [Function: read],
  readSync: [Function: readSync],
  readv: [Function: readv],
  readvSync: [Function: readvSync],
  readFile: [Function: readFile],
  readFileSync: [Function: readFileSync],
  readlink: [Function: readlink],
  readlinkSync: [Function: readlinkSync],
  realpath: [Function: realpath] { native: [Function] },
  realpathSync: [Function: realpathSync] { native: [Function] },
  rename: [Function: rename],
  renameSync: [Function: renameSync],
  rmdir: [Function: rmdir],
  rmdirSync: [Function: rmdirSync],
  stat: [Function: stat],
  statSync: [Function: statSync],
  symlink: [Function: symlink],
  symlinkSync: [Function: symlinkSync],
  truncate: [Function: truncate],
  truncateSync: [Function: truncateSync],
  unwatchFile: [Function: unwatchFile],
  unlink: [Function: unlink],
  unlinkSync: [Function: unlinkSync],
  utimes: [Function: utimes],
  utimesSync: [Function: utimesSync],
  watch: [Function: watch],
  watchFile: [Function: watchFile],
  writeFile: [Function: writeFile],
  writeFileSync: [Function: writeFileSync],
  write: [Function: write],
  writeSync: [Function: writeSync],
  writev: [Function: writev],
  writevSync: [Function: writevSync],
  Dir: [Function: Dir],
  Dirent: [Function: Dirent],
  Stats: [Function: Stats],
  ReadStream: [Getter/Setter],
  WriteStream: [Getter/Setter],
  FileReadStream: [Getter/Setter],
  FileWriteStream: [Getter/Setter],
  _toUnixTimestamp: [Function: toUnixTimestamp],
  F_OK: 0,
  R_OK: 4,
  W_OK: 2,
  X_OK: 1,
  constants: [Object: null prototype] {
    UV_FS_SYMLINK_DIR: 1,
    UV_FS_SYMLINK_JUNCTION: 2,
    O_RDONLY: 0,
    O_WRONLY: 1,
    O_RDWR: 2,
    UV_DIRENT_UNKNOWN: 0,
    UV_DIRENT_FILE: 1,
    UV_DIRENT_DIR: 2,
    UV_DIRENT_LINK: 3,
    UV_DIRENT_FIFO: 4,
    UV_DIRENT_SOCKET: 5,
    UV_DIRENT_CHAR: 6,
    UV_DIRENT_BLOCK: 7,
    S_IFMT: 61440,
    S_IFREG: 32768,
    S_IFDIR: 16384,
    S_IFCHR: 8192,
    S_IFBLK: 24576,
    S_IFIFO: 4096,
    S_IFLNK: 40960,
    S_IFSOCK: 49152,
    O_CREAT: 64,
    O_EXCL: 128,
    UV_FS_O_FILEMAP: 0,
    O_NOCTTY: 256,
    O_TRUNC: 512,
    O_APPEND: 1024,
    O_DIRECTORY: 65536,
    O_NOATIME: 262144,
    O_NOFOLLOW: 131072,
    O_SYNC: 1052672,
    O_DSYNC: 4096,
    O_DIRECT: 16384,
    O_NONBLOCK: 2048,
    S_IRWXU: 448,
    S_IRUSR: 256,
    S_IWUSR: 128,
    S_IXUSR: 64,
    S_IRWXG: 56,
    S_IRGRP: 32,
    S_IWGRP: 16,
    S_IXGRP: 8,
    S_IRWXO: 7,
    S_IROTH: 4,
    S_IWOTH: 2,
    S_IXOTH: 1,
    F_OK: 0,
    R_OK: 4,
    W_OK: 2,
    X_OK: 1,
    UV_FS_COPYFILE_EXCL: 1,
    COPYFILE_EXCL: 1,
    UV_FS_COPYFILE_FICLONE: 2,
    COPYFILE_FICLONE: 2,
    UV_FS_COPYFILE_FICLONE_FORCE: 4,
    COPYFILE_FICLONE_FORCE: 4
  },
  promises: [Getter]
}
undefined

Update-3) This may be helpful: https://github.com/nwjs/nw.js/issues/7183

...