2016-09-19 32 views
1

我在電子構建一個小應用程序,並需要發送一個過濾器對象與RegExp從渲染器進程到主進程。我用下面的代碼中渲染過程調用的方法上主要過程:通過電子ipc的RegExp變成普通的對象

const remote = require('electron').remote, 
     Filter = remote.require('./filter.js'), 
     filterInstance = new Filter(); 

let filter = { 
    $regex: new RegExp(/inventaris/i) 
}; 

filterInstance.find(filter); 

在渲染過程filter.$regex instanceof RegExp返回true。 關於主進程filter.$regex instanceof RegExp retuns false。

經過一點挖掘,我發現主工藝filter.$regex.constructor確實返回[Function: RegExp]

的問題是,第三方庫(NeDB)檢查變量真正的正則表達式使用:

exports.isRegExp = function(obj){return Object.prototype.toString.call(obj) === '[object RegExp]'}; 

返回假。除此之外,正則表達式根本不起作用,沒有將其包裝在new RegExp()中。

+0

'新的RegExp(/.../)'看起來不對。 '/.../'已經是'RegExp'對象。 – melpomene

+0

'/ inventaris/i'和'new RegExp('inventaris','i')'給出完全相同的結果 –

+0

我認爲你將不得不使用'eval(filter。$ regex)'。 –

回答

0

一般來說,通過Electron IPC發送的任何內容都會先被序列化爲JSON,如果您撥打JSON.stringify(/inventaris/i),您會得到{},這可能會被髮送。由於默認序列化在這種情況下不起作用,因此您需要將Regexp轉換爲將被序列化爲表單,然後在另一端反序列化之後可以將其轉換回Regexp。例如:

const originalRegex = /inventaris/i 
// this is what should be sent via IPC 
const payload = { source: regex.source, flags: regex.flags } 
// convert the payload back to a Regexp on the other end 
const reconstructedRegex = new Regexp(payload.source, payload.flags)